query array mongodb code example

Example 1: how to get array object value in mongodb

db.products.aggregate([
    {$unwind: "$ratings"},
    {$match: {'ratings.user': ObjectId("5f6e2e0b70eb0208fc8401a1")}}
])

Example 2: mongodb find element in array

db.yourCollection.find( { array: "element" } )

Example 3: mongodb find array with element

// Finds all documents that have a property named "tags"
// which has at least one array element matching "red"
db.inventory.find( { tags: "red" } )

Example 4: how to get array object value in mongodb

db.test.aggregate([
    {$match: {'shapes.color': 'red'}},
    {$project: {
        shapes: {$filter: {
            input: '$shapes',
            as: 'shape',
            cond: {$eq: ['$$shape.color', 'red']}
        }},
        _id: 0
    }}
])

Example 5: find string element in an array mongodb

db.articles.find({
    "stock.country" : "01",
    "stock.warehouse.code" : "02"
}).pretty();

Example 6: how to query array of object in mongoos

User.findOne({'local.rooms': {$elemMatch: {name: req.body.username}}}, function (err, user) {

        if (err){
            return done(err);
        }    

        if (user) {
            console.log("ROOM NAME FOUND");
            req.roomNameAlreadyInUse = true;
            next();

        } else {
            req.roomNameAlreadyInUse = false;
            console.log("ROOM NAME NOT FOUND");
            next();

        }

    });

Tags:

Misc Example