Mongoid分组多个嵌入式文档

时间:2016-06-10 16:04:02

标签: mongodb mongoid

我有一些大致有以下结构的文件:

{
 "_id": "derp",
  "name": "thing",
  "animal": {
    "_id": "abc",
    "stuff": [
      "blah",
      "wah"
    ]
  },
},
{
  "_id": "nerp",
  "person": {
    "_id": "bc",
    "enough": [
      "lah",
      "ah",
      "mwah"
    ]
  }
}

我正在计算数组中的行“stuff”和“够”。我最初认为我可以放松一下,但如果我为每个嵌入式文件“人”和“动物”调用一次,那么我将一无所获。

我最终做了单独的查询来获取每个内部数组的“东西”和“足够”的计数,但我想在一个查询中完成所有操作。

有谁知道如何获取每个这些的计数然后将它们放在像“object_count”这样的单独字段中?

1 个答案:

答案 0 :(得分:1)

After a chat and question update - this is working solution on test data set:

var unwind = {
    $unwind : "$array"
}
var project = {
    $project : {
        _id : 1,
        array : {
            $cond : [{
                    $ne : ["$a", []]
                }, "$a", "$b"]
        }
    }
}

var group = {
    $group : {
        _id : "$_id",
        a : {
            $push : "$animal.stuff"
        },
        b : {
            $push : "$person.enough"
        }
    }
}
var group2 = {
    $group : {
        _id : "$_id",
        sum : {
            $sum : 1
        }
    }
}

db.info.aggregate([group, project, unwind, unwind, group2])

Main idea is to put all stuff into one array, then unwind (as we are pushing then we need to unwind twice) and finally count.