如何在mongodb中嵌套对象内?

时间:2015-12-10 15:19:35

标签: node.js mongodb

我有一个名为 bikes 的集合,如下所示:

{
    "fname": "foo",
    "indian":"hero-corps"
    "brands": [
        {
            "region": "asia",
            "type": "terrain"
        }
    ]
}

通过这样的帖子获取json(我们将其命名为 jsonBody ):

{
  "indian": "hero-corps",
  "someKeyA": "someValueA",
}

我正在使用以下mongo更新查询:

 db.collection(bikes).update({"indian":"hero-corps"},{$set:jsonBody}, {upsert:true});

问题在于它在主对象内部进行插入,我只想在嵌套对象品牌中使用 jsonBody 进行插入。我如何实现这一目标?

实际结果:

{
    "fname": "foo",
    "indian": "hero-corps",
    "brands": [
       {
          "region": "asia",
          "type": "terrain"
       }
    ],
    "indian": "hero-corps",
    "someKeyA": "someValueA",
}

预期结果:

{
    "fname": "foo",
    "indian": "hero-corps",
    "brands": [
        {
            "region": "asia",
            "type": "terrain",
            "someKeyA": "someValueA",
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

我不确定这是否是您要执行的操作,但我确定它将提供您想要的格式。

db.collection(bikes).update({“ indian”:“ hero-corps”},{$ push:{“ brands”:jsonBody}},{upsert:true});