2

if i have this collection:

db.createCollection("misMensajes", {max: 100});

And documents with this distribution:

    db.misMensajes.insert(
    {
    "FechaEnvío": new Date("2015-06-22"),
    "Texto": "bla",
    "Destinatarios":[
        {
            "Nombre": "Pepa",
            "Edad": 15,
            "Apodo": "P"
        },
        {
            "Nombre": "Juan",
            "Edad": 16,
            "Apodo": "J"
        }
    ]
    }
);

What i want to do is a query to get the documents that have for "Destinatarios" "Edad" greater than 15 and less than 18. I don't know how to query "inside" the array "Destinatarios". I am starting in mongo and I don't understand many things. What I have until now is:

db.misMensajes.find({
    $and:[
        {Edad:{$gt:15}},
        {Edad:{$lt:18}}
    ]
});

But this is not giving me what I need.

0

3 Answers 3

2

To query inside an array, you need to use the dot notation for the field name, Destinatarios.Edad in this case:

db.misMensajes.find({
    $and: [
        { 'Destinatarios.Edad': { $gt: 15 } },
        { 'Destinatarios.Edad': { $lt: 18 } }
    ]
})

Also note that you don't need $and in this case:

db.misMensajes.find({
    'Destinatarios.Edad': { $gt: 15, $lt: 18 }
})

For more complex queries, you might need to use the $elemMatch operator.

Sign up to request clarification or add additional context in comments.

Comments

0

Please use $elemMatch. Here is the query.

db.misMensajes.find( { Destinatarios: { $elemMatch: { $and:[ {Edad:{$gt:15}}, {Edad:{$lt:18}} ] } } } );

Comments

0

Refer the find-doc to have a better understanding on how to use find query based on fields of an array.

To do find based on greater than and less than (as per your requirement) value, use $gt and $lt of mongodb.

So your can use as below :-

db.misMensajes.find({
$and: [
    { 'Destinatarios.Edad': { $gt: 15 } },
    { 'Destinatarios.Edad': { $lt: 18 } }
]
}).toArray(function(err, result)
   {
       console.log(results); //results will be an array of objects, containing all the records, which matches the query
    }

NOTE:- The above query will return the parent record, which matches the condition.

Destinatarios will have all the objects, not only the objects that matches the query.

If you want to get specific objects of Destinatarios array, you have to use aggregate.

2 Comments

Thak you! it really helps!
Glad it helped you.

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.