Reputation: 4482
Hey so how do I query a specific array item that belongs to a user's friend collection.
Here is the query:
Friend.find({userId: req.signedCookies.userid, 'friendStatus.labels': req.body.searchLabels
}, function(err, users) {
This broken down is the userId is a way to find the signed In User's document then I want to just access the labels inside the labels array that is nested in an object that is inside the friendStatus array...
here is an example of a document:
> 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")
}
and the current query returns the whole document when I use the callback users, but I just want to pull this out of it for the matching labels:
{
"favorites" : 1,
"fuId" : ObjectId("520a4905c24d995410000001"),
"labels" : [
"new",
"old"
],
"notes" : "He likes me",
"status" : 3
},
Upvotes: 1
Views: 136
Reputation: 324
You can use the aggregation framework to achieve this, specifically the $match
and $project
operators. $match
matches documents much like a regular query, and $project
allows you to select which fields to return in the query output. An aggregate query for your setup might look like this:
Friend.aggregate([{$match: {userId: req.signedCookies.userid,'friendStatus.labels': req.body.searchLabels}}, {$project: {'friendStatus.labels': 1}}])
More documentation can be found here: http://docs.mongodb.org/manual/reference/aggregation/operators/
Upvotes: 5