Home > Blockchain >  update one element of array of objects in mongodb
update one element of array of objects in mongodb

Time:11-05

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
}

CodePudding user response:

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"}}}}])
  • Related