mongodb get array element code example

Example 1: mongodb find element in array

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

Example 2: 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 3: mongodb array field contains

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

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
    }}
])