2013-06-26 241 views
0

我已经测试了以下聚集在mongodb外壳上,它工作正常,但是它似乎并没有与猫鼬一起工作。我已经搜索了类似的主题和问题,但他们的解决方案并不能解决我的问题Mongodb聚合不与猫鼬

文档结构是这样的

{ 
    name, 
    id, 

    contacts:[{ 
    contactId, //I need an array of this field 
    dateAdded 
    }, { 
    contactId, 
    dateAdded 
    }, 
    {}..] 
} 

的mongooose模式是:

var AccountSchema = new mongoose.Schema({ 
    email:  { type: String, unique: true }, 
    password: { type: String }, 
    name: { 
     first: { type: String }, 
     last: { type: String }, 
     full: { type: String } 
    }, 
    contacts: [Contact] 
    }); 

,这里是聚集:

Account.aggregate({ 
    $match: { _id: accountId } 
}, { 
    $unwind:"$contacts" 
}, 
{ 
    $group: { 
    _id: '$_id', 
    list: { $push:'$contacts.accountId' } 
    } 
}, { 
    $project: { 
    _id: 0, 
    contacts: 1 
    } 
}, function(err, doc) { 
    // var l=doc.result[0].list; 
    callback(doc); 
}); 

在MongoDB的外壳,汇聚返回contactID的数组,如下所示,但它返回一个Mongoose上的空数组

{ 
    "result" : [ 
    { 
     "_id" : null, 
     "list" : [ 
     ObjectId("xxxbnbnb2013-06-23T16:24:03.785Z"), 
     ObjectId("mnmnmnmui2013-06-23T16:24:04.688Z") 
     ] 
    } 
    ], 
    "ok" : 1 
} 

回答

3

您的查询似乎格式正确,我认为您刚应该投影“列表”时才投影“联系人”。我试图格式化我的数据像你的,下面的查询为我工作。在外壳:

db.accounts.aggregate( 
{ $unwind:"$contacts" }, 
{ $group: { 
    _id: '$_id', 
    list: { $push:'$contacts.contactId' } 
    } 
}, 
{ $project: { _id: 0, list: 1 }}) 

,或者使用猫鼬框架,

Account.aggregate(
    { $unwind:"$contacts" }, 
    { $group: { 
      _id: '$_id', 
      list: { $push:'$contacts.contactId' }}}, 
    { $project: { 
      _id: 0, 
      list: 1 }}, 
    function (err, res) { 
      if (err) //handle error; 
      console.log(res); 
      } 
); 

既然你已经尽力抑制你的聚集查询的最终输出的“_id”字段中,我假设您真的只是想获取所有帐户中所有联系人列表的名单,而不想将其链接回特定帐户。如果你想留下与contactIds的一个长长的清单(而不是较小的文档,每个原始帐户一个列表),你可以改为运行此聚集查询:

db.accounts.aggregate( 
{ $unwind:"$contacts" }, 
{ $group: { 
    _id: "allcontacts", 
    list: { $push:'$contacts.contactId' } 
    }} 
) 

,或者使用猫鼬框架,

Account.aggregate(
    { $unwind:"$contacts" }, 
    { $group: { 
      _id: "allcontacts", 
      list: { $push:'$contacts.contactId' }}}, 
    function (err, res) { 
      if (err) ; 
      console.log(res); 
      } 
    );