在两个小节mongodb中执行查询和抓取结果

我正在使用mongoose来处理我的数据库。

我有以下模型:

var DeviceSchema = mongoose.Schema({ type: Number, pushId: String }); 

type属性可以是0或1。

我想要执行一个查询,抓取所有文档,并以下列格式检索结果:

 { fstType: [ { _id: "545d533e2c21b900000ad234", type: 0, pushId: "123" }, { _id: "545d533e2c21b900000ad235", type: 0, pushId: "124" }, ], sndType: [ { _id: "545d533e2c21b900000ad236", type: 1, pushId: "125" }, { _id: "545d533e2c21b900000ad237", type: 1, pushId: "126" }, ] } 

那可能吗? 我想在一个单一的查询中做到这一点。

谢谢。

那可能吗? 我想在一个单一的查询中做到这一点。

是。 有可能的。 您可以通过以下aggregationstream水线操作来实现所需的结果。

  • Sort升序排列type参数。
  • 将具有相同typelogging组合在一起,为每个组构build一​​组文档。 在这个阶段之后,只有两个logging会出现,每个logging都有一个名为items的属性,这个属性是每个组的logging数组。
  • 由于我们的logging按typesorting, first组将包含types为0logging, first组包含types为1

最后,我们合并这些组,并根据它们的type为它们分别命名。

 var model = mongoose.model('collection',DeviceSchema); model.aggregate([ {$sort:{"type":-1}}, {$group:{"_id":"$type", "items":{$push:"$$ROOT"}, "type":{$first:"$type"}}}, {$project:{"items":{$cond:[{$eq:["$type",0]}, {"firstType":"$items"}, {"secondType":"$items"}]}}}, {$group:{"_id":null, "firstType":{$first:"$items.firstType"}, "secondType":{$last:"$items.secondType"}}}, {$project:{"_id":0,"firstType":1,"secondType":1}} ], function (err, result) { if (err) { console.log(err); return; } console.log(result); }); 

O / P:

 { firstType: [ { _id: '545d533e2c21b900000ad234', type: 0, pushId: '123' }, { _id: '545d533e2c21b900000ad235', type: 0, pushId: '124' } ], secondType: [ { _id: '545d533e2c21b900000ad236', type: 1, pushId: '125' }, { _id: '545d533e2c21b900000ad237', type: 1, pushId: '126' } ] }