如何更新MongoDB文档中的数组元素匹配条件? [英] How do I update Array Elements matching criteria in a MongoDB document?
本文介绍了如何更新MongoDB文档中的数组元素匹配条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有数组字段的文档,类似于此:
I have a document with an array field, similar to this:
{
"_id" : "....",
"Statuses" : [
{ "Type" : 1, "Timestamp" : ISODate(...) },
{ "Type" : 2, "Timestamp" : ISODate(...) },
//Etc. etc.
]
}
如何通过指定其状态值来更新特定状态项目的时间戳?
How can I update a specific Status item's Timestamp, by specifying its Type value?
推荐答案
在mongodb shell中,您可以这样做
From mongodb shell you can do this by
db.your_collection.update(
{ _id: ObjectId("your_objectid"), "Statuses.Type": 1 },
{ $set: { "Statuses.$.Timestamp": "new timestamp" } }
)
所以相当于C#
var query = Query.And(
Query.EQ("_id", "your_doc_id"),
Query.EQ("Statuses.Type", 1)
);
var result = your_collection.Update(
query,
Update.Set("Statuses.$.Timestamp", "new timestamp", UpdateFlags.Multi,SafeMode.True)
);
这将更新特定文档,如果要更新整个集合,则可以删除_id过滤器
This will update the specific document, you can remove _id filter if you wanted to update the whole collection
这篇关于如何更新MongoDB文档中的数组元素匹配条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文