推入mongodb中的一系列文档

时间:2018-07-03 04:06:40

标签: javascript arrays json mongodb mongoose

哪个运算符用于将新问题推送到问题数组中?我已经获得了以下格式的文档。哪个mongo db运算符用于将新问题插入到问题数组中,条件是我在给定的ChapterID和subchapterId中前进。

例如,我想在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.",

          }
        ]
      }
    ]
  }

3 个答案:

答案 0 :(得分:1)

您可以尝试

const title = "this is the new question"

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

答案 1 :(得分:0)

您可以将$ push与update一起使用

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

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

答案 2 :(得分:0)

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

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