Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

meteor - Insert element into nested arrays in MongoDB

I am new to mongoDB. I am having some trouble in updating the records in mongoDB collection.

How to add elements into array likes into the embedded record

I have a embedded collection like:

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2"
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

I want to update the record as

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2",
        "userID3" // How to write query to add this element.
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

Please provide the query to add the element shown in comment. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two possibilities here:

  1. Since you don't have an unique identifier for the comments, the only way to update an specific item on the comments array is to explicitly indicate the index you are updating, like this:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM"},
      { $push: { "comments.0.likes": "userID3" }}
    );
    
  2. If you add an unique identifier for the comments, you can search it and update the matched item, without worrying with the index:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM", "comments._id": "id1"},
      { $push: { "comments.$.likes": "userID3" }}
    );
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...