mongodb - 如果不存在则创建文档,否则推送到数组 [英] mongodb - create doc if not exist, else push to array
问题描述
我有一个格式如下的文档:
I have a document in the following form:
{
"_id" : ObjectId("4d2d8deff4e6c1d71fc29a07"),
"user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0",
"events" : [
{
"profile" : 10,
"data" : "....."
}
{
"profile" : 10,
"data" : "....."
}
{
"profile" : 20,
"data" : "....."
}
...
]
}
我想要某种upsert
语句.它需要添加一个 event
到 user_id
的 events
数组,以防已经存在这样的文档,否则它需要使用event
项目.
I'd like to have some sort of upsert
statement. It needs to add an event
to the events
array for user_id
in case there is already such doc exist, else it needs to create the doc with the event
item.
能做到吗?
推荐答案
您可以在 Mongo 中进行 upserts,请参阅 Mongo 文档:
You can do upserts in Mongo, see "Upserts with Modifiers" from the Mongo doc:
您可以使用带有修饰符的 upsert手术.在这种情况下,修饰符将应用于更新标准成员和结果对象将被插入.
You may use upsert with a modifier operation. In such a case, the modifiers will be applied to the update criteria member and the resulting object will be inserted.
您需要的查询将如下所示:
The query you need will look like:
db.events.update( { "user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0" },
{ $push : { "events" : { "profile" : 10, "data" : "X"}}}, {"upsert" : true});
这篇关于mongodb - 如果不存在则创建文档,否则推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!