如何用mongo db中的现有文档填充缺失的字段?

时间:2017-04-07 05:17:33

标签: mongodb mongodb-query

我有像

这样的文件
   [{ _id:.., mailTitle:"hello", broadcastMessage:"how are u"}]
   [{ _id:.., mailTitle:"hello john", broadcastMessage:"how are u john"}]
   [{ _id:.., mailTitle:"hello", broadcastMessage:"how are u john",
   user_id:"1", dateSent:"12/12/2016"
   }]

现在我想在前两个和所有其他文档中添加user_id:“1”,dateSent:“12/12/2016”。

请帮助!!!

1 个答案:

答案 0 :(得分:2)

使用update(已弃用):

 db.collection.update(
           { "user_id": {$exists: false}, "dateSent": {$exists: false} },
           { $set:
              {
                user_id : 1,
                dateSent: "12/12/2016", (Use a UTC Date object instead of string)
              }
           },
        {
            multi: true
        }
    );

使用updateMany

db.collection.updateMany(
      { "user_id": {$exists: false}, "dateSent": {$exists: false} },
      { $set:
              {
                user_id : 1,
                dateSent: "12/12/2016", (Use a UTC Date object instead of string)
              }
      }
   );

以上内容将获取所有没有名为user_iddateSent字段的文档,然后设置这些字段。希望这会有所帮助。