簡體   English   中英

mongodb 向數組中插入一個新字段

[英]mongodb insert a new field into an array

我正在嘗試向對象數組插入一個新字段

{
    "_id": "543356fe0c9af6066e68970c",
    "createdDate": "2014-10-06 07:59 pm",
    "cancle": false,
    "eventDate": "2014/12/12",
    "eventstatus": true,
    "location": "chennai",
    "userId": "54310801e2659ecc3650100b",
    "createdBy": "one",
    "eventName": "tea ",
    "__v": 0,
    "friends": [
        {
            "userId": "54310814e2659ecc3650100c",
            "userName": "two",
            "phoneNumber": "22222222"
        },
        {
            "userId": "54310945e2659ecc3650100d",
            "userName": "three",
            "phoneNumber": "33333333"
        },
        {
            "userId": "54334def7e85de48638d1069",
            "userName": "four",
            "phoneNumber": "44444444"
        }
    ]
}

我想將 "status": 0 添加到 friends 數組中的所有對象

我嘗試使用 addtoset、push 和多種方式,將其添加為好友數組中的新 object。

db.events.update({},{$push:{ "friends" : {"status" : 0} }},false,true)
db.events.update({},{$addToSet : {'friends' : $each: [{ 'status':0}]}},false,true)

請讓我知道我做錯了什么。 謝謝你的幫助

您可以使用它來更新陣列

db.events.find().forEach(function(e){
  var t=e.friends;
  t.forEach(function(e){
    e.status=0
  });
  db.events.update({_id:e._id},{$set:{friends:t}})
})

在你的mongo終端中運行它。

不知道代碼的問題,但我有正確的代碼

var cursor = db.events.find();
cursor.forEach(function(item)
{
    var friends = item.friends;
    friends.forEach(function(elem) 
    {
        elem['status'] = '....',
    })    
    db.events.update({_id: item._id}, item);    
});

它正在使用mongo shell,但我不知道javascript

在Java和Springs MongoTemplate中,您可以向數組中的所有條目添加一個新字段:

final Query query = new Query(Criteria.where("states.$[].date").exists(false));    
final Update update = new Update().set("states.$[].stateSetBy", "SYSTEM");
mongoTemplate.updateMulti(query, update, "<collection_name>");

在此示例中,您有一個包含“狀態”數組的文檔,並希望為此數組的每個條目添加一個新字段。

最重要的部分是$ []來解決數組中的每個條目

請參閱: https//docs.mongodb.com/manual/reference/operator/update-array/

這個答案也可以幫助你: https://stackoverflow.com/a/67162997/7724011

它使用帶有聚合管道的updateMany方法迭代數組項,然后使用$mergeObjects為每個項添加新屬性。

up時需要添加多個true和call函數

db.events.update({},{$push:{ "friends" : {"status" : 0} }},{ multi: true },function(e,update){});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM