MongoDB的 - 创建的文档,如果不存在,否则推阵 [英] mongodb - create doc if not exist, else push to array

查看:449
本文介绍了MongoDB的 - 创建的文档,如果不存在,否则推阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式的文件:

{
"_id" : ObjectId("4d2d8deff4e6c1d71fc29a07"),
"user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0",
"events" : [
        {
                "profile" : 10,
                "data" : "....."
        }
        {
                "profile" : 10,
                "data" : "....."
        }
        {
                "profile" : 20,
                "data" : "....."
        }
        ...
   ]
 }

我想有某种的UPSERT 语句。它需要一个事件添加到事件阵列 USER_ID 的情况下,已经有这样的文档存在,否则就需要创建一个事件项目文档。

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.

可以在做什么?

推荐答案

您可以做upserts在蒙戈,请参阅Upserts使用修改器,从的蒙戈DOC

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.

你需要看起来像查询:

db.events.update( { "user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0" }, 
{ $push : { "events" : { "profile" : 10, "data" : "X"}}}, true);

这篇关于MongoDB的 - 创建的文档,如果不存在,否则推阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆