如何编写查询对象内部数组的mongo查询?

时间:2017-08-14 07:22:46

标签: arrays mongodb mongodb-query

假设我有一个mongo数据库,如下所示:

[
  {
    dec: 5972,
    bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0]
  },
  {
    dec: 397250,
    bin: [1,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0]
  },
  {
    dec: 5,
    bin: [0,1,0,1]
  },
  {
    dec: 123,
    bin: [0,1,1,1,1,0,1,1]
  }
]

如何查询数据库以向我提供bin属性中“0”和“1”的数量相等的所有对象。 例如,我希望结果只是:

{
  dec: 5,
  bin: [0,1,0,1]
}       

1 个答案:

答案 0 :(得分:1)

你走了:

db.test.aggregate([
{
    $project: {
        dec: "$dec",
        bin: "$bin",
        original_bin: "$bin"
    }
},

{
    $unwind: "$bin"
},
{
    $group: {
        _id: {
            dec: "$dec",
            bin: "$bin",
            original_bin: "$original_bin"
        },

        total: {
            $sum: 1
        }
    }
},
{
    $group: {
        _id: {dec: "$_id.dec", original_bin: "$_id.original_bin"},
        sums: {
            $addToSet: "$total"
        }
    }
},
{
    $match: {
        sums: {
            $size: 1
        }
    }
},
{
    $project: {
        _id: 0,
        dec: "$_id.dec",
        bin: "$_id.original_bin"
    }
}
]);

我有这样的示例数据:

{"dec":1,bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0]}
{"dec":2,bin: [0,1,0,1,0,0]}
{"dec":3,bin: [1,0,1,0,1,0]}
{"dec":4,bin: [0,1,0,0]}
{"dec":5,bin: [0,0,0,1,1,1]}
{"dec":6,bin: [0,1]}

给定对样本数据的查询返回所需的数组:

{ "dec" : 6, "bin" : [ 0, 1 ] }
{ "dec" : 3, "bin" : [ 1, 0, 1, 0, 1, 0 ] }
{ "dec" : 5, "bin" : [ 0, 0, 0, 1, 1, 1 ] }