DEV Community

loading...

Some useful array operations in MongoDB

ats1999 profile image Rahul kumar ・2 min read

Data Schema

{ "_id" : ObjectId("60966503a06708c0a9d05b51"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b52"), "item" : "notebook", "qty" : 50, "tags" : [ "red", "blank" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b53"), "item" : "paper", "qty" : 100, "tags" : [ "red", "blank", "plain" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b54"), "item" : "planner", "qty" : 75, "tags" : [ "blank", "red" ], "dim_cm" : [ 22.85, 30 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b55"), "item" : "postcard", "qty" : 45, "tags" : [ "blue" ], "dim_cm" : [ 10, 15.25 ] }
Enter fullscreen mode Exit fullscreen mode

Query

1 - Fine by order

Suppose you would like to find the item which contains blank and red in the specified order, then you can write the queries like below.

db.items.find({tags:["blank","red"]})

// output
{ "_id" : ObjectId("60966503a06708c0a9d05b51"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b54"), "item" : "planner", "qty" : 75, "tags" : [ "blank", "red" ], "dim_cm" : [ 22.85, 30 ] }
Enter fullscreen mode Exit fullscreen mode

Note: Order of the query matters
If you have specified [red,blank] then you'll get only [red,blank] not [blank,red]

2 - Find without order

If you don't want the exact order then you can use $all operator of MongoDB.

db.items.find({tags:{$all:["red"]}})

// output
{ "_id" : ObjectId("60966503a06708c0a9d05b51"), "item" : "journal", "qty" : 25, "tags" : [ "blank", "red" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b52"), "item" : "notebook", "qty" : 50, "tags" : [ "red", "blank" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b53"), "item" : "paper", "qty" : 100, "tags" : [ "red", "blank", "plain" ], "dim_cm" : [ 14, 21 ] }
{ "_id" : ObjectId("60966503a06708c0a9d05b54"), "item" : "planner", "qty" : 75, "tags" : [ "blank", "red" ], "dim_cm" : [ 22.85, 30 ] }
Enter fullscreen mode Exit fullscreen mode

3 - Check for single element

You can directly provide string in the query parameter.

 db.items.find({tags:"red"})
Enter fullscreen mode Exit fullscreen mode

Find all items which contain red as an element, anywhere in the array.

3 - Check for single (Conditionally)

You can provide operators for the conditionality check

db.items.find({dim_cm:{$gt:21,$lt:50}})
Enter fullscreen mode Exit fullscreen mode

The above query will find all items, which has any element inside dim_cm array which is less than 50 and greater than 21.

Explore

You can explore more here https://docs.mongodb.com/manual/tutorial/query-arrays/

Thanku

Discussion (0)

Forem Open with the Forem app