Query an Array

This page provides examples in:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go

This page provides examples of query operations on array fields using thedb.collection.find() method in themongo shell. The examples on this page use theinventory collection. To populate the inventorycollection, run the following:

This page provides examples of query operations on array fields usingMongoDB Compass. The examples on thispage use the inventory collection. Populate theinventory collection with the following documents:

This page provides examples of query operations on array fields using thepymongo.collection.Collection.find() method in thePyMongoPython driver. The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations on array fields using thecom.mongodb.client.MongoCollection.find method in the MongoDBJava Synchronous Driver.

Tip

The driver provides com.mongodb.client.model.Filtershelper methods to facilitate the creation of filterdocuments. The examples on this page use these methods tocreate the filter documents.

The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations on array fields using theCollection.find() method inthe MongoDB Node.js Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using theMongoDB\Collection::find()method in theMongoDB PHP Library.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using themotor.motor_asyncio.AsyncIOMotorCollection.find()method in the Motordriver. The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations on array fields using thecom.mongodb.reactivestreams.client.MongoCollection.find)method in the MongoDB Java Reactive Streams Driver.

The examples on this page use the inventorycollection. To populate the inventory collection, run thefollowing:

This page provides examples of query operations on array fields using theMongoCollection.Find()method in theMongoDB C# Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using theMongoDB::Collection::find() methodin theMongoDB Perl Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using theMongo::Collection#find()method in theMongoDB Ruby Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using thecollection.find()(implicite:org.mongodb.scala.bson.DefaultHelper.DefaultsTo[C,TResult],implicitct:scala.reflect.ClassTag[C]):org.mongodb.scala.FindObservable[C]) methodin theMongoDB Scala Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

This page provides examples of query operations on array fields using theCollection.Findfunction in theMongoDB Go Driver.The examples on this page use the inventory collection. Topopulate the inventory collection, run the following:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.insertMany([
  2. { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
  3. { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
  4. { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
  5. { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
  6. { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
  7. ]);

You can run the operation in the web shell below:

  1. [
  2. { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
  3. { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
  4. { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
  5. { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
  6. { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
  7. ]

For instructions on inserting documents in MongoDB Compass, seeInsert Documents.

  1. db.inventory.insert_many([
  2. {"item": "journal",
  3. "qty": 25,
  4. "tags": ["blank", "red"],
  5. "dim_cm": [14, 21]},
  6. {"item": "notebook",
  7. "qty": 50,
  8. "tags": ["red", "blank"],
  9. "dim_cm": [14, 21]},
  10. {"item": "paper",
  11. "qty": 100,
  12. "tags": ["red", "blank", "plain"],
  13. "dim_cm": [14, 21]},
  14. {"item": "planner",
  15. "qty": 75,
  16. "tags": ["blank", "red"],
  17. "dim_cm": [22.85, 30]},
  18. {"item": "postcard",
  19. "qty": 45,
  20. "tags": ["blue"],
  21. "dim_cm": [10, 15.25]}])
  1. collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
  3. Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
  4. Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
  5. Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
  6. Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
  7. ));
  1. await db.collection('inventory').insertMany([
  2. {
  3. item: 'journal',
  4. qty: 25,
  5. tags: ['blank', 'red'],
  6. dim_cm: [14, 21]
  7. },
  8. {
  9. item: 'notebook',
  10. qty: 50,
  11. tags: ['red', 'blank'],
  12. dim_cm: [14, 21]
  13. },
  14. {
  15. item: 'paper',
  16. qty: 100,
  17. tags: ['red', 'blank', 'plain'],
  18. dim_cm: [14, 21]
  19. },
  20. {
  21. item: 'planner',
  22. qty: 75,
  23. tags: ['blank', 'red'],
  24. dim_cm: [22.85, 30]
  25. },
  26. {
  27. item: 'postcard',
  28. qty: 45,
  29. tags: ['blue'],
  30. dim_cm: [10, 15.25]
  31. }
  32. ]);
  1. $insertManyResult = $db->inventory->insertMany([
  2. [
  3. 'item' => 'journal',
  4. 'qty' => 25,
  5. 'tags' => ['blank', 'red'],
  6. 'dim_cm' => [14, 21],
  7. ],
  8. [
  9. 'item' => 'notebook',
  10. 'qty' => 50,
  11. 'tags' => ['red', 'blank'],
  12. 'dim_cm' => [14, 21],
  13. ],
  14. [
  15. 'item' => 'paper',
  16. 'qty' => 100,
  17. 'tags' => ['red', 'blank', 'plain'],
  18. 'dim_cm' => [14, 21],
  19. ],
  20. [
  21. 'item' => 'planner',
  22. 'qty' => 75,
  23. 'tags' => ['blank', 'red'],
  24. 'dim_cm' => [22.85, 30],
  25. ],
  26. [
  27. 'item' => 'postcard',
  28. 'qty' => 45,
  29. 'tags' => ['blue'],
  30. 'dim_cm' => [10, 15.25],
  31. ],
  32. ]);
  1. await db.inventory.insert_many([
  2. {"item": "journal",
  3. "qty": 25,
  4. "tags": ["blank", "red"],
  5. "dim_cm": [14, 21]},
  6. {"item": "notebook",
  7. "qty": 50,
  8. "tags": ["red", "blank"],
  9. "dim_cm": [14, 21]},
  10. {"item": "paper",
  11. "qty": 100,
  12. "tags": ["red", "blank", "plain"],
  13. "dim_cm": [14, 21]},
  14. {"item": "planner",
  15. "qty": 75,
  16. "tags": ["blank", "red"],
  17. "dim_cm": [22.85, 30]},
  18. {"item": "postcard",
  19. "qty": 45,
  20. "tags": ["blue"],
  21. "dim_cm": [10, 15.25]}])
  1. Publisher<Success> insertManyPublisher = collection.insertMany(asList(
  2. Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
  3. Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
  4. Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
  5. Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
  6. Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
  7. ));
  1. var documents = new[]
  2. {
  3. new BsonDocument
  4. {
  5. { "item", "journal" },
  6. { "qty", 25 },
  7. { "tags", new BsonArray { "blank", "red" } },
  8. { "dim_cm", new BsonArray { 14, 21 } }
  9. },
  10. new BsonDocument
  11. {
  12. { "item", "notebook" },
  13. { "qty", 50 },
  14. { "tags", new BsonArray { "red", "blank" } },
  15. { "dim_cm", new BsonArray { 14, 21 } }
  16. },
  17. new BsonDocument
  18. {
  19. { "item", "paper" },
  20. { "qty", 100 },
  21. { "tags", new BsonArray { "red", "blank", "plain" } },
  22. { "dim_cm", new BsonArray { 14, 21 } }
  23. },
  24. new BsonDocument
  25. {
  26. { "item", "planner" },
  27. { "qty", 75 },
  28. { "tags", new BsonArray { "blank", "red" } },
  29. { "dim_cm", new BsonArray { 22.85, 30 } }
  30. },
  31. new BsonDocument
  32. {
  33. { "item", "postcard" },
  34. { "qty", 45 },
  35. { "tags", new BsonArray { "blue" } },
  36. { "dim_cm", new BsonArray { 10, 15.25 } }
  37. }
  38. };
  39. collection.InsertMany(documents);
  1. $db->coll("inventory")->insert_many(
  2. [
  3. {
  4. item => "journal",
  5. qty => 25,
  6. tags => [ "blank", "red" ],
  7. dim_cm => [ 14, 21 ]
  8. },
  9. {
  10. item => "notebook",
  11. qty => 50,
  12. tags => [ "red", "blank" ],
  13. dim_cm => [ 14, 21 ]
  14. },
  15. {
  16. item => "paper",
  17. qty => 100,
  18. tags => [ "red", "blank", "plain" ],
  19. dim_cm => [ 14, 21 ]
  20. },
  21. {
  22. item => "planner",
  23. qty => 75,
  24. tags => [ "blank", "red" ],
  25. dim_cm => [ 22.85, 30 ]
  26. },
  27. {
  28. item => "postcard",
  29. qty => 45,
  30. tags => ["blue"],
  31. dim_cm => [ 10, 15.25 ]
  32. }
  33. ]
  34. );
  1. client[:inventory].insert_many([{ item: 'journal',
  2. qty: 25,
  3. tags: ['blank', 'red'],
  4. dim_cm: [ 14, 21 ] },
  5. { item: 'notebook',
  6. qty: 50,
  7. tags: ['red', 'blank'],
  8. dim_cm: [ 14, 21 ] },
  9. { item: 'paper',
  10. qty: 100,
  11. tags: ['red', 'blank', 'plain'],
  12. dim_cm: [ 14, 21 ] },
  13. { item: 'planner',
  14. qty: 75,
  15. tags: ['blank', 'red'],
  16. dim_cm: [ 22.85, 30 ] },
  17. { item: 'postcard',
  18. qty: 45,
  19. tags: ['blue'],
  20. dim_cm: [ 10, 15.25 ] }
  21. ])
  1. collection.insertMany(Seq(
  2. Document("""{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }"""),
  3. Document("""{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }"""),
  4. Document("""{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }"""),
  5. Document("""{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }"""),
  6. Document("""{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }""")
  7. )).execute()
  1. docs := []interface{}{
  2. bson.D{
  3. {"item", "journal"},
  4. {"qty", 25},
  5. {"tags", bson.A{"blank", "red"}},
  6. {"dim_cm", bson.A{14, 21}},
  7. },
  8. bson.D{
  9. {"item", "notebook"},
  10. {"qty", 50},
  11. {"tags", bson.A{"red", "blank"}},
  12. {"dim_cm", bson.A{14, 21}},
  13. },
  14. bson.D{
  15. {"item", "paper"},
  16. {"qty", 100},
  17. {"tags", bson.A{"red", "blank", "plain"}},
  18. {"dim_cm", bson.A{14, 21}},
  19. },
  20. bson.D{
  21. {"item", "planner"},
  22. {"qty", 75},
  23. {"tags", bson.A{"blank", "red"}},
  24. {"dim_cm", bson.A{22.85, 30}},
  25. },
  26. bson.D{
  27. {"item", "postcard"},
  28. {"qty", 45},
  29. {"tags", bson.A{"blue"}},
  30. {"dim_cm", bson.A{10, 15.25}},
  31. },
  32. }
  33.  
  34. result, err := coll.InsertMany(context.Background(), docs)

Match an Array

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

To specify equality condition on an array, use the querydocument { <field>: <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument { <field>: <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument { <field>: <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument eq( <field>, <value>) where <value> isthe exact array to match, including the order of theelements.

To specify equality condition on an array, use the querydocument { <field>: <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument [ <field> => <value> ] where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument { <field>: <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument eq( <field>, <value>) where <value> isthe exact array to match, including the order of theelements.

To specify equality condition on an array, construct a filterusing the Eq method:

  1. Builders<BsonDocument>.Filter.Eq(<field>, <value>)

<value> is the exact array to match, including theorder of the elements.

To specify equality condition on an array, use the querydocument { <field> => <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument { <field> => <value> } where <value> is theexact array to match, including the order of the elements.

To specify equality condition on an array, use the querydocument equal( <field>, <value> ) where <value> isthe exact array to match, including the order of theelements.

The following example queries for all documents where the field tagsvalue is an array with exactly two elements, "red" and "blank",in the specified order:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { tags: ["red", "blank"] } )

Copy the following filter into the Compass query bar and clickFind:

  1. { tags: ["red", "blank"] }

../../_images/compass-array-match-exact.png

  1. cursor = db.inventory.find({"tags": ["red", "blank"]})
  1. FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
  1. const cursor = db.collection('inventory').find({
  2. tags: ['red', 'blank']
  3. });
  1. $cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
  1. cursor = db.inventory.find({"tags": ["red", "blank"]})
  1. FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
  1. var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
  1. client[:inventory].find(tags: ['red', 'blank'])
  1. var findObservable = collection.find(equal("tags", Seq("red", "blank")))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{{"tags", bson.A{"red", "blank"}}},
  4. )

If, instead, you wish to find an array that contains both the elements"red" and "blank", without regard to order or other elements inthe array, use the $all operator:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { tags: { $all: ["red", "blank"] } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { tags: { $all: ["red", "blank"] } }

../../_images/compass-array-match-all.png

  1. cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
  1. findIterable = collection.find(all("tags", asList("red", "blank")));
  1. const cursor = db.collection('inventory').find({
  2. tags: { $all: ['red', 'blank'] }
  3. });
  1. $cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);
  1. cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
  1. findPublisher = collection.find(all("tags", asList("red", "blank")));
  1. var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { tags => { '$all' => [ "red", "blank" ] } } );
  1. client[:inventory].find(tags: { '$all' => ['red', 'blank'] })
  1. findObservable = collection.find(all("tags", "red", "blank"))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"tags", bson.D{{"$all", bson.A{"red", "blank"}}}},
  5. })

Query an Array for an Element

  • Mongo Shell
  • Python
  • Java (Sync)
  • Node.js
  • PHP
  • Other
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

To query if the array field contains at least one elementwith the specified value, use the filter{ <field>: <value> } where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filter{ <field>: <value> } where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filtereq( <field>, <value>) where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filter{ <field>: <value> } where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filter[ <field> => <value> ] where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filter{ <field>: <value> } where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filtereq( <field>, <value>) where value is the element value.

To query if the array field contains at least one elementwith the specified value, construct a filter using theEq method:

  1. Builders<BsonDocument>.Filter.Eq(<field>, <value>)

<value> is the element value to match.

To query if the array field contains at least one elementwith the specified value, use the filter

{ <field> => <value> } where value is the element value.

To query if the array field contains at least one elementwith the specified value, use the filter{ <field> => <value> } where <value> is the element value.

To query if the array field contains at least one elementwith the specified value, use the filterequal( <field>, <value> ) where <value> is the element value.

The following example queries for all documents where tags is anarray that contains the string "red" as one of its elements:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { tags: "red" } )

Copy the following filter into the Compass query bar and clickFind:

  1. { tags: "red" }

../../_images/compass-array-elem-match.png

  1. cursor = db.inventory.find({"tags": "red"})
  1. findIterable = collection.find(eq("tags", "red"));
  1. const cursor = db.collection('inventory').find({
  2. tags: 'red'
  3. });
  1. $cursor = $db->inventory->find(['tags' => 'red']);
  1. cursor = db.inventory.find({"tags": "red"})
  1. findPublisher = collection.find(eq("tags", "red"));
  1. var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { tags => "red" } );
  1. client[:inventory].find(tags: 'red')
  1. findObservable = collection.find(equal("tags", "red"))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"tags", "red"},
  5. })
  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field>: { <operator1>: <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field>: { <operator1>: <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field>: { <operator1>: <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document. For example:

  1. and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field>: { <operator1>: <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. [ <array field> => [ <operator1> => <value1>, ... ] ]

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field>: { <operator1>: <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document. For example:

  1. and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

To specify conditions on the elements in the array field,use query operators in thequery filter document. For example:

  1. var builder = Builders<BsonDocument>.Filter;
  2. builder.And(builder.Eq(<array field>, <value1>), builder.Lt(<array field>, <value2>));

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field> => { <operator1> => <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. { <array field> => { <operator1> => <value1>, ... } }

To specify conditions on the elements in the array field,use query operators in thequery filter document:

  1. and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

For example, the following operation queries for all documents where the arraydim_cm contains at least one element whose value is greater than25.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { dim_cm: { $gt: 25 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { dim_cm: { $gt: 25 } }

../../_images/compass-array-query-op.png

  1. cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
  1. findIterable = collection.find(gt("dim_cm", 25));
  1. const cursor = db.collection('inventory').find({
  2. dim_cm: { $gt: 25 }
  3. });
  1. $cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);
  1. cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
  1. findPublisher = collection.find(gt("dim_cm", 25));
  1. var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { "dim_cm" => { '$gt' => 25 } } );
  1. client[:inventory].find(dim_cm: { '$gt' => 25 })
  1. findObservable = collection.find(gt("dim_cm", 25))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"dim_cm", bson.D{
  5. {"$gt", 25},
  6. }},
  7. })

Specify Multiple Conditions for Array Elements

When specifying compound conditions on array elements, you can specifythe query such that either a single array element meets these conditionor any combination of array elements meets the conditions.

Query an Array with Compound Filter Conditions on the Array Elements

The following example queries for documents where the dim_cm arraycontains elements that in some combination satisfy the queryconditions; e.g., one element can satisfy the greater than 15condition and another element can satisfy the less than 20condition, or a single element can satisfy both:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { dim_cm: { $gt: 15, $lt: 20 } }

../../_images/compass-array-compound-filter.png

  1. cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
  1. findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
  1. const cursor = db.collection('inventory').find({
  2. dim_cm: { $gt: 15, $lt: 20 }
  3. });
  1. $cursor = $db->inventory->find([
  2. 'dim_cm' => [
  3. '$gt' => 15,
  4. '$lt' => 20,
  5. ],
  6. ]);
  1. cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
  1. findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
  1. var builder = Builders<BsonDocument>.Filter;
  2. var filter = builder.And(builder.Gt("dim_cm", 15), builder.Lt("dim_cm", 20));
  3. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { "dim_cm" => { '$gt' => 15, '$lt' => 20 } }
  3. );
  1. client[:inventory].find(dim_cm: { '$gt' => 15,
  2. '$lt' => 20 })
  1. findObservable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"dim_cm", bson.D{
  5. {"$gt", 15},
  6. {"$lt", 20},
  7. }},
  8. })

Query for an Array Element that Meets Multiple Criteria

Use $elemMatch operator to specify multiple criteria on theelements of an array such that at least one array element satisfies allthe specified criteria.

The following example queries for documents where the dim_cm arraycontains at least one element that is both greater than ($gt)22 and less than ($lt) 30:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }

../../_images/compass-array-compound-multiple-criteria.png

  1. cursor = db.inventory.find(
  2. {"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
  1. findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
  1. const cursor = db.collection('inventory').find({
  2. dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
  3. });
  1. $cursor = $db->inventory->find([
  2. 'dim_cm' => [
  3. '$elemMatch' => [
  4. '$gt' => 22,
  5. '$lt' => 30,
  6. ],
  7. ],
  8. ]);
  1. cursor = db.inventory.find(
  2. {"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
  1. findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
  1. var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find(
  2. { dim_cm => { '$elemMatch' => { '$gt' => 22, '$lt' => 30 } } }
  3. );
  1. client[:inventory].find(dim_cm: { '$elemMatch' => { '$gt' => 22,
  2. '$lt' => 30 } })
  1. findObservable = collection.find(elemMatch("dim_cm", Document("$gt" -> 22, "$lt" -> 30)))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"dim_cm", bson.D{
  5. {"$elemMatch", bson.D{
  6. {"$gt", 22},
  7. {"$lt", 30},
  8. }},
  9. }},
  10. })

Query for an Element by the Array Index Position

Using dot notation, you can specify query conditions for anelement at a particular index or position of the array. The array useszero-based indexing.

Note

When querying using dot notation, the field and nested field must beinside quotation marks.

The following example queries for all documents where the secondelement in the array dim_cm is greater than 25:

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "dim_cm.1": { $gt: 25 } }

../../_images/compass-array-match-by-index.png

  1. cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
  1. findIterable = collection.find(gt("dim_cm.1", 25));
  1. const cursor = db.collection('inventory').find({
  2. 'dim_cm.1': { $gt: 25 }
  3. });
  1. $cursor = $db->inventory->find(['dim_cm.1' => ['$gt' => 25]]);
  1. cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
  1. findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
  1. var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { "dim_cm.1" => { '$gt' => 25 } } );
  1. client[:inventory].find('dim_cm.1' => { '$gt' => 25 })
  1. findObservable = collection.find(gt("dim_cm.1", 25))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"dim_cm.1", bson.D{
  5. {"$gt", 25},
  6. }},
  7. })

Query an Array by Array Length

Use the $size operator to query for arrays by number ofelements. For example, the following selects documents where the arraytags has 3 elements.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala
    • Go
  1. db.inventory.find( { "tags": { $size: 3 } } )

Copy the following filter into the Compass query bar and clickFind:

  1. { "tags": { $size: 3 } }

../../_images/compass-array-query-by-size.png

  1. cursor = db.inventory.find({"tags": {"$size": 3}})
  1. findIterable = collection.find(size("tags", 3));
  1. const cursor = db.collection('inventory').find({
  2. tags: { $size: 3 }
  3. });
  1. $cursor = $db->inventory->find(['tags' => ['$size' => 3]]);
  1. cursor = db.inventory.find({"tags": {"$size": 3}})
  1. findPublisher = collection.find(size("tags", 3));
  1. var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
  2. var result = collection.Find(filter).ToList();
  1. $cursor = $db->coll("inventory")->find( { tags => { '$size' => 3 } } );
  1. client[:inventory].find(tags: { '$size' => 3 })
  1. findObservable = collection.find(size("tags", 3))
  1. cursor, err := coll.Find(
  2. context.Background(),
  3. bson.D{
  4. {"tags", bson.D{
  5. {"$size", 3},
  6. }},
  7. })

Additional Query Tutorials

For additional query examples, see: