简体   繁体   中英

update one element of array of objects in mongodb

I have the following documents:

{
  _id: ObjectId('111111111111111111114444'),
  books: [
    {
      id: ObjectId('111111111111111111113333'),
      pictures: []
    },
    {
      id: ObjectId('111111111111111111112222'),
      pictures: []
    }
  ],
  // others attributes
}

What I need to do is to add an element to pictures . Keep in mind that I have the documentId which is the id of the document, and the bookId which is the Id of an element of books .

If I want to add the element {description: "nice picture"} to the document 111111111111111111114444 in the book 111111111111111111113333 , the updated document would look like

{
  _id: ObjectId('111111111111111111114444'),
  books: [
    {
      id: ObjectId('111111111111111111113333'),
      pictures: [
        {
          description: "nice picture"
        }
      ]
    },
    {
      id: ObjectId('111111111111111111112222'),
      pictures: []
    }
  ],
  // others attributes
}

Query

  • pipeline update requires MongoDB >= 4.2
  • filter the "_id"
  • map on books if id=2 merge objects, with the pictures containing the new element
  • else if not id=2 dont change the book

*i used 1,2,3 for ids (its the same code)

Test code here

update({"_id" : 1},
[{"$set": 
   {"books": 
     {"$map": 
       {"input": "$books",
        "in": 
        {"$cond": 
          [{"$eq": ["$$book.id", 2]},
           {"$mergeObjects": 
             ["$$book",
               {"pictures": 
                 {"$concatArrays": 
                   ["$$book.pictures", [{"description": "nice picture"}]]}}]},
           "$$book"]},
        "as": "book"}}}}])

Edit

Query

  • if pictures isnt't array(or dont exists), creates an empty array

Test code here

update({"_id" : 1},
[{"$set": 
    {"books": 
      {"$map": 
        {"input": "$books",
          "in": 
          {"$cond": 
            [{"$eq": ["$$book.id", 2]},
              {"$mergeObjects": 
                ["$$book",
                  {"pictures": 
                    {"$concatArrays": 
                      [{"$cond": 
                          [{"$isArray": ["$$book.pictures"]}, "$$book.pictures",
                            []]},
                        [{"description": "nice picture"}]]}}]},
              "$$book"]},
          "as": "book"}}}}])

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