Daulet Cheri
Daulet Cheri

Reputation: 57

How to get some documents of array in MongoDB

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 ? enter image description here

Here i want to get username , password and first document of questions which is {question:"dawdaw",answered:0}

Upvotes: 0

Views: 86

Answers (2)

chridam
chridam

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

Rohit Jain
Rohit Jain

Reputation: 2092

You can use slice like this

db.users.find({},{"questions":{$slice:1}})

Hope it will help

Upvotes: 1

Related Questions