MongoDB Read Array Document

MongoDB Read Array Document

MongoDB 05-02-2023 Saheb Sutradhar

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

 

 

 

 

 

 

 

 

 

Related Posts

Card image cap

MongoDB Basic and CRUD Operations

MongoDB 02-09-2022 Saheb Sutradhar

MongoDB Basic and CRUD Operations ...

Card image cap

MongoDB read operation findOne() and find()

MongoDB 05-02-2023 Saheb Sutradhar

MongoDB read operation findOne() and find() ...

Card image cap

MongoDB upsert

MongoDB 02-03-2023 Saheb Sutradhar

MongoDB upsert ...

Card image cap

MongoDB $unset

MongoDB 02-03-2023 Saheb Sutradhar

MongoDB $unset ...

Card image cap

MongoDB $rename

MongoDB 02-03-2023 Saheb Sutradhar

MongoDB $rename ...

Card image cap

MongoDB array update operation

MongoDB 13-03-2023 Saheb Sutradhar

MongoDB array update operation ...