MongoDB使用upsert递增嵌套文档

时间:2015-12-09 16:43:39

标签: mongodb nested upsert

是否可以执行一个MongoDB查询,该查询会increment嵌套文档的字段,并在文档不存在时创建该嵌套文档?

示例:

{
  id: ...
  nestedArray: [
    {kind: "foo", times: 10}
  ]
}

假设我想增加一个nestedArray.$.times字段kind: "bar",但数组中不存在bar?因此在执行看起来像

的查询之后
db.mycollection.update({id: "100", nestedArray:{$elemMatch: {kind: "bar"}}}, {$inc: {'nestedArray.$.times': 1}}, {upsert: true})

文件看起来像这样:

{
  id: ...
  nestedArray: [
    {kind: "foo", times: 10},
    {kind: "bar", times: 1}
  ]
}

当然,如果找不到整个文档(不仅仅是嵌套文档),那么会自动创建一个文档。

1 个答案:

答案 0 :(得分:1)

作为一种解决方法,可以通过两个更新查询来实现,

<强>查询1

db.mycollection.update(
  {id:"400","nestedArray.kind": "bar"},
  {$inc: {"nestedArray.$.times":1}}
)

这是一个直接的查询,它增加了nestedArray.kind的nestedArray.times值为“bar”。如果找不到该文档则无效。

查询2

此查询处理插入新文档/推入嵌套数组,以防id存在匹配文档。

db.mycollection.update(
  {id:"400","nestedArray.kind": {$ne:"bar"}},
  {$push: {"nestedArray": {kind:"bar","times":1}}},
  {upsert:true}
)

此查询在文档中搜索id,其中nestedArray.kind没有条形值。如果找到这样的文档,{kind:"bar","times":1}将被推送到nestedArray。如果未找到,则会创建一个新文档,其中{kind:"bar","times":1}是nestedArray中的唯一值。

相关问题