MongoDB Read Array Document
Data
[
{
name: 'Iphone 13 pro',
filter: [ { filterid: 1, option: 2 }, { filterid: 2, option: 3 } ],
price: { price: 33453 },
_5g: { is5g: true }
},
]
How to query Array data?
Scenario : I want to filter all the documents where option : 3
db.collection.find( { "filter.option" : 3 } )
{
_id: ObjectId("63deb331bdfbb73b0247581f"),
name: 'Iphone 11',
filter: [ 'apple', 'price0-5000' ],
price: { price: 23453 },
network: '5G'
}
Scenario : I want to filter all the documents where filter array is having 'apple' ,'price0-5000'
db.collection.find( { filter : [ 'apple' , 'price0-5000' ]} )
Problem with above example is it will follow the element sequence ['apple','price0-5000']
if any document is having ['price0-5000' , 'apple']
this will not get filtered
Solution :
db.collection.find( { filter : { $all : [ 'apple' , 'price0-5000' ] } } )
$all :
$all :[] doesn't check the array element's sequence , it only checks if all the elements are there in the array of the document or not
$elemMatch :
[
{
name: 'Iphone 13 pro',
filter: [ { filterid: 1, option: 2 }, { filterid: 2, option: 3 } ],
price: { price: 33453 },
_5g: { is5g: true }
},
]