【问题标题】:Mongodb query - check existing documentsMongodb查询-检查现有文档
【发布时间】:2018-04-16 14:36:42
【问题描述】:

是否可以在 Ruby 中编写代码,如果我的数据库中已经存在一个文档来聚合新文档和已经存在的文档,如果它不存在,则将新文档添加到数据库中?

我知道如何进行聚合,但在这种情况下我不知道如何使用 $exists。

为了更新现有的文档,我已经创建了,但是我想如果我想推送一个完整的哈希,我不能使用它:

db.coll.update({"title" : "Document"},
 {$push:{"comments":{
     "user":'user2',
     "message": 'My second comment',
     "dateCreated": new Date(2013,11,10,2,35),
     "like": 0
}}})

【问题讨论】:

    标签: ruby mongodb mongodb-query


    【解决方案1】:

    在更新查询中使用upsert: true 选项。

    来自 mongodb 手册:

    Upsert:如果设置为 true,则在没有文档与查询条件匹配时创建一个新文档。默认值为false,没有找到匹配时不插入新文档。

    您的查询可能如下所示:

    db.coll.update({"title" : "Document"}, {$push: {
        "comments":{
            "user":'user2',
            "message": 'My second comment',
            "dateCreated": new Date(2013,11,10,2,35),
            "like": 0
            }
        },
        {upsert: true}
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-04
      • 2021-02-25
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多