嘿所以如何查询属于用户的朋友集合的特定数组项.
这是查询:
Friend.find({userId: req.signedCookies.userid, 'friendStatus.labels': req.body.searchLabels
}, function(err, users) {
Run Code Online (Sandbox Code Playgroud)
这个细分是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")
}
Run Code Online (Sandbox Code Playgroud)
当我使用回调用户时,当前查询返回整个文档,但我只想将其从匹配标签中拉出来:
{
"favorites" : 1,
"fuId" : ObjectId("520a4905c24d995410000001"),
"labels" : [
"new",
"old"
],
"notes" : "He likes me",
"status" : 3
},
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用聚合框架来实现此目的,特别是$match和$project运算符.$match匹配文档很像常规查询,并$project允许您选择在查询输出中返回哪些字段.您的设置的聚合查询可能如下所示:
Friend.aggregate([{$match: {userId: req.signedCookies.userid,'friendStatus.labels': req.body.searchLabels}}, {$project: {'friendStatus.labels': 1}}])
Run Code Online (Sandbox Code Playgroud)
可在此处找到更多文档:http://docs.mongodb.org/manual/reference/aggregation/operators/
| 归档时间: |
|
| 查看次数: |
125 次 |
| 最近记录: |