这是我的第一个 mongodb 项目,我在 mongodb 中有这个文档结构,我正在尝试检索一个特定的用户帐户(每个用户帐户都有一个联系人数组),然后从这个用户帐户获取一个 ID 字段数组的用户联系人,然后将此数组作为参数传递给另一个查询,我这样做是为了避免必须遍历用户联系人数组才能获取 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);
});
});
};
编辑 //我现在已经能够使用以下查询获得一个联系人 ID 字段数组
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
}