Doua Beri
Doua Beri

Reputation: 10939

MongoDb - Query an Array

Based on the MongoDB documentation https://docs.mongodb.com/manual/tutorial/query-arrays/

I have this collection:

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

Are these queries equivalent ?

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

and

db.inventory.find( { tags: "red" } )

If they have different purposes , when to use one instead of the other?

Upvotes: 0

Views: 174

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Yes, those two queries are equivalent. You would only use $all when you want to query for the docs containing multiple tags values:

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

This query would match all but the last document in your example collection.

Upvotes: 1

Related Questions