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 } ] }
Pregunta
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?
Solución
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 } ] }