0

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}

Daulet Cheri
  • 57
  • 1
  • 1
  • 5
  • 1
    Don't use images to provide code samples. Include the code itself (formatted as code) so that others can easily copy and paste it to reproduce the problem themselves. – JohnnyHK Oct 11 '15 at 16:09
  • Possible duplicate of http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection – JohnnyHK Oct 11 '15 at 16:30

2 Answers2

1

You can use slice like this

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

Hope it will help

Rohit Jain
  • 2,052
  • 17
  • 19
1

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" : "asd@mail.ru",
    "password" : "asd",
    "questions" : [ 
        {
            "question" : "dawdaw",
            "answered" : 0
        }
    ]
}
chridam
  • 100,957
  • 23
  • 236
  • 235