简体   繁体   English

更新mongodb中对象数组的一个元素

[英]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 .我需要做的是在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 .请记住,我有documentIddocumentId的 id,而bookIdbooks元素的 Id。

If I want to add the element {description: "nice picture"} to the document 111111111111111111114444 in the book 111111111111111111113333 , the updated document would look like如果我想将元素{description: "nice picture"}1111111111111111111114444一书中的文档1111111111111111111113333 ,更新后的文档看起来像

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

Query询问

  • pipeline update requires MongoDB >= 4.2管道更新需要 MongoDB >= 4.2
  • filter the "_id"过滤“_id”
  • map on books if id=2 merge objects, with the pictures containing the new element如果id=2合并对象,则在书籍上映射,其中图片包含新元素
  • else if not id=2 dont change the book否则如果不是id=2不要换书

*i used 1,2,3 for ids (its the same code) *我使用 1,2,3 作为 ids(它的代码相同)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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