0

I have the following data on a mongodb:

{
    "name" : "bla",
    "log" : [
        {
            "A" : 1,
            "B" : 10
        },
        {
            "A" : 2,
            "B" : 20
        }
    ]
}

I understand how to return all values of A from the mongoshell:

 db.test.find({},{'name':1,'log.A':1})
{ "_id" : ObjectId("52712539c99a2fc6f6088cd4"), "name" : "bla", "log" : [ { "A" : 1 }, { "A" : 2 } ] }

but how can I limit the output of A to only the first element? This is the output that I extect to have:

{ "_id" : ObjectId("52712539c99a2fc6f6088cd4"), "name" : "bla", "log.A" : 1, "log.B":10}

I don't mind in having log.A or just A, or even having some [ ] in the output, as soon as it is always only one entry for A and for B

how can I do it?

1 Answer 1

2

You can use the $slice array projection operator to do that:

db.test.find({}, {name: 1, 'log.A':1, log: {$slice: 1}})

Outputs:

{ "_id" : ObjectId("..."), "name" : "bla", "log" : [  {  "A" : 1 } ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.