最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - mongodb insert a new field into an array - Stack Overflow

programmeradmin1浏览0评论

I am trying to insert a new field to an array of objects

{
    "_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"
        }
    ]
}

I want to add "status" : 0 to all the objects inside friends array

I tried using addtoset, push and multiple ways, its adding as a new object in friends array.

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

Please let me know what i am doing wrong. Thanks for your help

I am trying to insert a new field to an array of objects

{
    "_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"
        }
    ]
}

I want to add "status" : 0 to all the objects inside friends array

I tried using addtoset, push and multiple ways, its adding as a new object in friends array.

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

Please let me know what i am doing wrong. Thanks for your help

Share Improve this question edited Sep 22, 2017 at 18:01 CommunityBot 11 silver badge asked Oct 13, 2014 at 8:02 Balu LoganathanBalu Loganathan 1611 gold badge2 silver badges9 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 15

You can use this to update the arrays

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}})
})

Run this in your mongo terminal.

Don't know about problem with the code but I have the right code for it

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);    
});

It is working with mongo shell, but I don't know about javascript

In Java and Springs MongoTemplate you can add a new field to all entries in a array with:

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>");

in this example you have a document with an array of "states" and want to add a new field to every entry of this array.

most important part is the $[] to address every entry in the array

see: https://docs.mongodb.com/manual/reference/operator/update-array/

This answer can also help you: https://stackoverflow.com/a/67162997/7724011

It uses the updateMany method with aggregation pipeline to iterate over the array items and then use $mergeObjects to add new properties to each one of them.

need to add multi true and call function require when up

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

评论列表(0)

  1. 暂无评论