【问题标题】:Mongodb aggregation not working with mongooseMongodb聚合不适用于猫鼬
【发布时间】:2013-06-24 07:27:42
【问题描述】:

我已经在 mongodb shell 上测试了以下聚合,它工作正常,但它似乎不适用于 mongoose。我搜索了类似的主题和问题,但他们的解决方案并没有解决我的问题。

文档结构是这样的

{
  name,
  id,

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

猫鼬模式是:

 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 shell上,聚合返回一个contactID数组,如下图,但在Mongoose上返回一个空数组

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

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您的查询格式似乎正确,我认为您只是在应该投影“列表”时投影了“联系人”。我尝试像您一样格式化我的数据,以下查询对我有用。在外壳中:

    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”字段,我假设您真的只是对获取所有帐户中的所有联系人 ID 的列表感兴趣,而不是对将它们链接回特定帐户。如果您希望留下一个长长的联系人 ID 列表(而不是每个原始帐户一个列表的小文档),您可以运行此聚合查询:

    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);
              }
         );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2017-08-03
      • 2021-04-20
      • 2020-12-30
      • 2015-05-19
      • 1970-01-01
      相关资源
      最近更新 更多