推入 mongodb 中的文档数组

Posted

技术标签:

【中文标题】推入 mongodb 中的文档数组【英文标题】:Push into an array of documents in mongodb 【发布时间】:2018-12-11 07:00:39 【问题描述】:

使用哪个运算符将新问题推送到问题数组中?我有以下格式的文档。如果给定了 chapterId 和 subchapterId,则使用哪个 mongo db 运算符将新问题插入问题数组中前进。

例如,我想在 subchapterId "1" 中插入一个新问题。

  

    "chapterId": "38",
    "subChapter": [
      

        "subchapterId": "1",
        "questions": [
          

            "title": "Either his however modern. Stop central owner color type out. Interview five beyond interesting type suddenly.",

          ,
          

            "title": "Amount himself foreign color moment gun together sit. Deal race range heart despite several. Rather activity eat dinner save mission western. Civil past public enter four then.",

          ,
          

            "title": "Four former operation. Class continue away treatment.\nResponsibility condition dinner realize everything. Sign scene order quality yet. Within sing statement skill popular southern whole."

          ,
          

            "title": "Where of coach nature ask page allow.\nType exist hotel time. Central site policy everyone safe. Official administration family somebody.",

          ,
          

            "title": "Necessary dark these much region. Form sometimes seek. Future according detail piece section.\nNear everything admit. Senior Republican draw as expert market.",

          
        ]
      ,
      

        "subchapterId": "2",
        "questions": [
          

            "title": "Audience still use group. Yourself building police. Play imagine serious reality population reach.\nHerself without member must think concern window finish."

          ,


          

            "title": "Rule trip manage still. Imagine religious above race something successful.\nOnce base American series. Low page quite allow. Customer maybe base leave way under blood.",

          ,
          

            "title": "Church audience anyone garden. Federal when individual style.Value billion morning need box whether. Coach traditional cold each us truth.",

          
        ]
      
    ]
  

【问题讨论】:

认为这可能会有所帮助***.com/questions/13987365/… 【参考方案1】:

你可以试试这个

const title = "this is the new question"

db.collection.update(
   "subChapter.subchapterId": "1" ,
   "$push":  "subChapter.$.questions":  title  
)

【讨论】:

【参考方案2】:

您可以将 $push 与更新一起使用

示例代码适用于 chapterId:38 和 subchapterId:1

db.collection_name.update( "chapterId":"38", "subChapter.subchapterId": "1" ,  $push:  "subChapter.$.questions":'title':'Newly added record' )

【讨论】:

【参考方案3】:

使用$addToSet 避免更新时对象数组中的重复项

db.yourcollectionName.update(        
  "subChapter.subchapterId" :"1"
,$addToSet:"subChapter.$.questions":title:"updated Object")

【讨论】:

以上是关于推入 mongodb 中的文档数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在 MongoDB 中推入具有精确键值的对象嵌套数组?

使用 Spring Data MongodB 更新嵌入式 mongodb 文档中的数组字段?

MongoDB:从多个文档中的数组中删除文档

使用 MongoDB 中的文档属性过滤器获取嵌入数组中的扁平文档数组

如何匹配 MongoDB 中的子文档数组?

MongoDB 更新数组数组中的文档字段