[英]Error when trying to update MongoDb array element
In my Azure CosmosDb MongoApi I have JSON with an embed array of documents. 在我的Azure CosmosDb MongoApi中,我具有带有嵌入式文档数组的JSON。
{
"_id": ObjectId("5a95745df886842904b82f71"),
"token": "value1",
"channel": "value2",
"urls":
[
{
"url": "<url1>",
"interval": "<int>"
},
{
"url": "<url2>"
"interval": "<int>"
}
]
}
I want to update "interval" field in a specific array element. 我想更新特定数组元素中的“间隔”字段。 Problem is when I use solutions like this or this , I end up with an exception: 问题是,当我使用像解决这个还是这个 ,我结束了一个例外:
MongoDB.Driver.MongoCommandException: Command findAndModify failed: Invalid BSON field name 'urls.$.interval'.
So, I decided to try running queries in Mongo Shell and got the same error: 因此,我决定尝试在Mongo Shell中运行查询,并得到了相同的错误:
{
"nMatched": 0,
"nUpserted": 0,
"nModified": 0,
"writeError":
{
"code": 2,
"errmsg": "Invalid BSON field name 'urls.$.interval'"
}
}
Here is my C# code: 这是我的C#代码:
var filterBuilder = Builders<User>.Filter;
var filter = filterBuilder.Where(p => p.Token == model.Token && p.Channel == model.Channel && p.Urls.Any( u => u.Url == model.Url));
var update = Builders<User>.Update.Set(p => p.Urls.ElementAt(-1).interval, 5);
await _context.Users.FindOneAndUpdateAsync<User>(filter, update);
Here is my MongoDb shell request: 这是我的MongoDb shell请求:
db.Users.update( {"urls.interval": 60}, {$set: {"urls.$.interval": 30}} );
My question is what is causing this exception and how can I avoid it? 我的问题是导致此异常的原因是什么,如何避免呢?
Positional operator is not currently supported by Cosmos DB. Cosmos DB当前不支持位置运算符。 Please use the following workaround: iterate over documents and array elements on the client side, change the required element and issue an update on the document with new array: For example, assuming you have a collection users of following elements: 请使用以下变通办法:在客户端上遍历文档和数组元素,更改所需的元素,并使用新数组在文档上发布更新:例如,假设您具有以下元素的集合用户:
{ "_id" : ObjectId("59d6b719708b990d6c9b3aca"), "tags" : [ { "id" : 1, "value" : "11" }, { "id" : 2, "value" : "22" }, { "id" : 3, "value" : "32" } ] }
…you can issue the following command to get one of the elements (with id=1 in this case) updated: …您可以发出以下命令来更新其中一个元素(在这种情况下,id = 1):
db.users.find().forEach( function(user) { user.tags.forEach( function(tag) { if (tag.id=="1") { tag.value = "Updated!"; db.users.updateOne({_id : user._id}, {$set: {"tags": user.tags}}); } } ); } );
You can adjust the condition in if() with even finer granularity than positional operator allows. 您可以在if()中以比位置运算符允许的更好的粒度来调整条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.