I ve got a collection users that look like this :
{
_id: myid,
name : 'blabla',
ia : {
[0]-> 'an id',
[1]-> 'a second id'
}
}
And i want to have only my first id of ia, so i tried something like that :
User.find({ _id: id, ia :{ key : indexia} }, ['ia']).populate('ia').run(rendu);
where id= myid, and indexia=0.
If i don t put that part : " ia :{ key : indexia}" i get all my ia... but i want only one.
Hope i was clear. Thanks
The MongoDB find()
command is intended to match an entire document.
When you run the following query
{ _id: id, ia :{ key : indexia} }
... this means "where _id
equals id
and ia
equals the object {key:0}
". That's probably not what you want.
If i don t put that part : " ia :{ key : indexia}" i get all my ia... but i want only one.
It sounds like you want to return a piece of a given document. The documentation for that is here. In your case it would look like this:
find({ _id: id}, { 'ia.0' : 1 })
The first part of the find will find the document. The second part will return specific fields.
Your collection appears to have the schema:
{ "_id" : "id",
"ia" : ["id1","id2","id3"],
etc.
}
In this case, the query to get just the first "id" of the "ia" field would be:
find({}, { "ia" : {$slice:1 } })
You can read more about $slice operator here. Mongoose documents its support for the $slice operator on the query page. Hope this helps!
Thanks for your help It worker like that:
User.find({ _id: id }).only('ia').slice('ia', indexia, 1).populate('ia').run(rendu);
The only('ia') don t work, but not a big deal.