2014-11-15 68 views
1

我正在使用猫鼬来处理我的数据库。在两个小节中执行查询和抓取结果mongodb

我有以下型号:

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" 
     }, 
    ] 
} 

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

谢谢。

+0

能否请您发布'user'和'device',样品输出的样本文件? – BatScream

+0

请参阅编辑。 ....... –

+0

太好了,让我试试吧。 – BatScream

回答

1

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

是的。有可能的。您可以通过以下aggregation流水线操作获得所需的结果。

  • Sorttype参数按升序排列。
  • Group记录在一起具有相同的type,构建每个组的 文件的数组。在此阶段之后,只有两个记录将为 ,每个记录具有一个称为items的属性,该属性是每个组的 记录的数组。
  • 由于我们的记录是由type排序,该first组将包含 记录与0类型和second1型。

最后,我们合并这些组,并根据它们的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' } ] }