如何检索子文档的特定字段数组 - mongodb

时间:2013-06-26 13:51:13

标签: mongodb mongoose

这是我的第一个mongodb项目,我在mongodb中有这个文档结构,我正在尝试检索一个特定的用户帐户(每个用户帐户都有一个联系人数组),从这个用户帐户,我将获得一个数组用户联系人的ID字段然后将此数组作为参数传递给另一个查询,我这样做是为了避免不得不遍历用户contacts数组以获取ID字段,这里是文档结构,查询我试过就在它下面

{
  name,
  id,

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

//
  var findByIdAll = function(accountId, callback) {
     var self=this;
          //Get the user account
      Account.findOne({_id:accountId}, function(err,doc) {

          /  After the user account has been obtained, the function below will
        // use an array of the users contactsId's to fetch the contact's accounts
          //please how do I obtain the array of contact Id's before reaching here                     

       self.Account.find({_id:{$in:[/array of contact Ids]}},function(err,results){
      callback(results);
    });
    });
  };

EDIT //我现在可以使用以下查询

获取contactID字段数组
 var r=db.accounts.aggregate({$match:{email:'m@live.com'}},{$unwind:"$contacts"},
       {$project:{_id:0,contacts:1}},{$group:{_id:'$_id',
       list:{$push:'$contacts.accountId'}}});

    The result I get from the query is 
  

[R

{
        "result" : [
                {
                        "_id" : null,
                        "list" : [
                                ObjectId("51c59a31c398c40c22000004"),
                                ObjectId("51c59a31c398c40c22000004")
                        ]
                }
        ],
        "ok" : 1
}

1 个答案:

答案 0 :(得分:3)

正常的MongoDB查询将始终为您提供具有相同结构的整个文档。 如果您只想获得文档的一部分或对其进行转换,则需要使用Aggregation Framework(并不像看起来那么难以理解,请尝试一下)。

在您的情况下,您可能必须在联系人中使用$unwind来分解数组,$match仅获取您想要的帐户,并$project根据需要显示数据。