Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从单个MongoDB查询中获取多个数据片_Mongodb_Nosql_Aggregation Framework - Fatal编程技术网

从单个MongoDB查询中获取多个数据片

从单个MongoDB查询中获取多个数据片,mongodb,nosql,aggregation-framework,Mongodb,Nosql,Aggregation Framework,好吧,假设我有一个名为Baz的文档集合,假设它看起来像: [ { _id: 1, foo: true, bar: true }, { _id: 2, foo: false, bar: true }, { _id: 3, foo: true, bar: false }, { _id: 1, foo: false, bar: false } ] 我想查询它并得到如下结果: [ { isFoo: [ { _id: 1, foo: true, b

好吧,假设我有一个名为Baz的文档集合,假设它看起来像:

[
    { _id: 1, foo: true, bar: true },
    { _id: 2, foo: false, bar: true },
    { _id: 3, foo: true, bar: false },
    { _id: 1, foo: false, bar: false }
]
我想查询它并得到如下结果:

[
    { isFoo: [
        { _id: 1, foo: true, bar: true },
        { _id: 3, foo: true, bar: false }
    ], isBar: [
        { _id: 1, foo: true, bar: true },
        { _id: 2, foo: false, bar: true }
    ]}
]
如您所见,它为我提供了一个包含
foo:true
的所有文档的数组,以及一个包含
bar:true
的所有文档的列表。这就是我想要的结局!提前感谢,所以社区

总之
可以针对Baz编写什么查询来获得所需的结果?

我认为
$facet
操作符几乎提供了您所需的内容,唯一的区别在于
$facet
您将从
聚合()
中获得一个包含两个数组字段的文档:

{
    "isFoo" : [
       {  "_id" : 1,  "foo" : true,  "bar" : true  },
       {  "_id" : 3,  "foo" : true,  "bar" : false  }
    ],
    "isBar" : [
       {  "_id" : 1,  "foo" : true,  "bar" : true },
       {  "_id" : 2,  "foo" : false, "bar" : true }
    ]
}


db.baz.aggregate([
  {$facet: {
    "isFoo": [
      {$match: {"foo": true}}
      ]
    ,"isBar": [
      {$match: {"bar": true}}
      ]
   }}
 ]);

我认为
$facet
操作符几乎提供了您想要的内容,唯一的区别是
$facet
您将从
aggregate()
返回一个带有两个数组字段的文档:

{
    "isFoo" : [
       {  "_id" : 1,  "foo" : true,  "bar" : true  },
       {  "_id" : 3,  "foo" : true,  "bar" : false  }
    ],
    "isBar" : [
       {  "_id" : 1,  "foo" : true,  "bar" : true },
       {  "_id" : 2,  "foo" : false, "bar" : true }
    ]
}


db.baz.aggregate([
  {$facet: {
    "isFoo": [
      {$match: {"foo": true}}
      ]
    ,"isBar": [
      {$match: {"bar": true}}
      ]
   }}
 ]);