嘿,我如何查询属于用户朋友集合的特定数组项。
以下是查询:
Friend.find({userId: req.signedCookies.userid, 'friendStatus.labels': req.body.searchLabels
}, function(err, users) {
这个细分是userId是一种查找已登录用户文档的方法然后我想只访问嵌套在friendStatus数组内的对象的labels数组中的标签...
这是一个文档示例:
> db.friends.find({'firstName': "test3"}).pretty()
{
"__v" : 0,
"_id" : ObjectId("520a4944c24d995410000008"),
"accepted_notifications" : true,
"added_notifications" : true,
"firstName" : "test3",
"firstNameTrue" : "test3",
"friendStatus" : [
{
"favorites" : 1,
"fuId" : ObjectId("520a4905c24d995410000001"),
"labels" : [
"new",
"old"
],
"notes" : "He likes me",
"status" : 3
},
{
"fuId" : ObjectId("520a4925c24d995410000004"),
"labels" : [ ],
"notes" : "sadwa",
"status" : 3
}
],
"lastName" : "test3s",
"lastNameTrue" : "TEST3s",
"notifications" : 0,
"userId" : ObjectId("520a4944c24d995410000007")
}
当我使用回调用户时,当前查询返回整个文档,但我只想将其从匹配标签中拉出来:
{
"favorites" : 1,
"fuId" : ObjectId("520a4905c24d995410000001"),
"labels" : [
"new",
"old"
],
"notes" : "He likes me",
"status" : 3
},
答案 0 :(得分:5)
您可以使用聚合框架来实现此目的,特别是$match
和$project
运算符。 $match
与常规查询非常匹配文档,$project
允许您选择在查询输出中返回哪些字段。您的设置的聚合查询可能如下所示:
Friend.aggregate([{$match: {userId: req.signedCookies.userid,'friendStatus.labels': req.body.searchLabels}}, {$project: {'friendStatus.labels': 1}}])
可在此处找到更多文档:http://docs.mongodb.org/manual/reference/aggregation/operators/