Reputation: 57
I have collection "users" where username , password,questions are stored . "questions" is an array of documents . I would like to get all users with some questions i.e username , password and an array of questions (some part) How can i do that from console or java ?
Here i want to get username , password and first document of questions which is {question:"dawdaw",answered:0}
Upvotes: 0
Views: 86
Reputation: 103365
Use $elemMatch
projection to get the desired result. The following find()
operation queries for all documents where the $elemMatch
projection returns only the first matching element of the questions
array where the question
field has a value of "dawdaw"
and answered
has 0
value:
db.users.find({},
{
"username": 1, "password": 1,
"questions": {
"$elemMatch": {
"question" : "dawdaw",
"answered" : 0
}
}
}
);
From the sample given, the operation returns the following document:
/* 0 */
{
"_id" : ObjectId("561a84ffaa233b38d803509a"),
"username" : "[email protected]",
"password" : "asd",
"questions" : [
{
"question" : "dawdaw",
"answered" : 0
}
]
}
Upvotes: 1
Reputation: 2092
You can use slice like this
db.users.find({},{"questions":{$slice:1}})
Hope it will help
Upvotes: 1