Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding array element in an object

Tags:

mongodb

nosql

"features" : {
    "en" : [ 
        {
            "translatable" : true,
            "capacity " : [ 
                "128GB", 
                "256GB"
            ]
        }, 
        {
            "translatable" : true,
            "material  " : [ 
                "Glass", 
                "Aluminium"
            ]
        }
    ]
}

I am finding 'capacity': '128GB' when I am using this query

db.getCollection('products').find({
    'features.en' : {
        $elemMatch : {
            'capacity' : {
                $in : ['128GB']
            }
        }
    }
})

But not fetching. If i query for 'translatable':true

db.getCollection('products').find({
    'features.en' : {
        $elemMatch : {
            'translatable' : true
        }
    }
})
like image 225
Mohammad Kashif Sulaiman Avatar asked Jun 14 '26 20:06

Mohammad Kashif Sulaiman


1 Answers

there is a tricky TYPO in your input document - so please check if capacity has a SPACE at the end

db.prod.aggregate([{
            $match : {
                "features.en.capacity " : "128GB"
            }
        },
    ]).pretty()

to get only array element that mets your criteria you can use this aggregation query:

db.prod.aggregate([{
            $unwind : "$features.en"
        }, {
            $match : {
                "features.en.translatable" : true
            }
        }, {
            $match : {
                "features.en.capacity " : "128GB"
            }
        },
    ]).pretty()
like image 62
profesor79 Avatar answered Jun 18 '26 01:06

profesor79