简体   繁体   中英

mongoDB: Can't add an field to an array object

This is how my db document looks like:

{
    "_id" : "aN2jGuR2rSzDx87LB",
    "content" : {
        "en" : [
            {
                "content" : "Item 1",
                "timestamp" : 1518811796
            }
        ]
    }
}

Now I need to add another field in the first object of the content.en array. The document itself gets selected by an ID. The result should be:

{
  "_id" : "aN2jGuR2rSzDx87LB",
  "content" : {
    "en" : [
      {
        "content" : "Item 1",
        "timestamp" : 1518811796,
        "user" : {
          "id" : 'userId'
        }
      }
    ]
  }
}

I tried to do it like this, but nothing is happening. I don't even get an error message.

Content.update(
  { _id: id },
  {
    $addToSet: {
      'content.en.0.user': {
        id: 'userId',
      }
    }
  }
)

Also I would like to use an variable for the language. How do I do that? Something like 'content.' + language + '.0.user' 'content.' + language + '.0.user' ...

$addToSet is useful when you want to add someting to an array. In your case you want to modify first element of your array (at index 0 ) so you should simply use $set (which is field update operator):

Content.update(
   { _id: "aN2jGuR2rSzDx87LB" },
   {
      $set: {
         "content.en.0.user": {
         id: "userId",
      }
   }
 }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM