Code: Select all
[
{
"Id": "a399f6c6-13b1-4060-8917-e99c54208165",
"Watchlists": [
{
"Id": "0fddfa7a-528d-4fa9-9019-e2f7d7699427",
"name": "MyWatchList",
"Symbols": [
{
"SymbolName": "USD",
"SymbolId": "0a61be6d-664f-4909-8743-83e202679abf"
}
]
},
{
"Id": "04280f42-0c02-4deb-9c47-4c255efb58d8",
"name": "MyWatchList2",
"Symbols": [
{
"SymbolName": "EURO",
"SymbolId": "be2fe40c-e289-4ef6-b43e-28a6e72b296c"
}
]
}
]
}
]
Ich habe geschrieben Arbeitscode in Mongoplayground – https://mongoplayground.net/p/v-udOKePMkQ
Code: Select all
db.collection.update({
"Id": "a399f6c6-13b1-4060-8917-e99c54208165"
},
{
$push: {
"Watchlists.$[element].Symbols": {
"SymbolName": "USD",
"SymbolId": "0a61be6d-664f-4909-8743-83e202679abf"
}
}
},
{
arrayFilters: [
{
"element.Id": "04280f42-0c02-4deb-9c47-4c255efb58d8",
"element.Symbols": {
"$not": {
"$elemMatch": {
"SymbolName": "USD"
}
}
}
}
],
upsert: true
})
Code: Select all
var baseFilter = Builders.Filter.Eq(x => x.UserId, userId);
var update = Builders.Update
.Push("Watchlists.$[d].Symbols", new Symbol { SymbolId = request.SymbolId, Name = request.SymbolName});
var filter1 = new BsonDocument("d.Id", $"{request.watchlistId}");
var filter2 = new BsonDocument("d.Symbols", new BsonDocument("$not", new BsonDocument("$elemMatch", new BsonDocument("SymbolId", $"{request.SymbolId}"))));
var arrayFilters = new List
{
new BsonDocumentArrayFilterDefinition(new BsonDocument("$and",new BsonArray(){ filter1, filter2}))
};
return await mongoCollection.FindOneAndUpdateAsync(
baseFilter,
update,
new FindOneAndUpdateOptions { IsUpsert = true, ReturnDocument = ReturnDocument.After, ArrayFilters = arrayFilters });