Navigation

Query an Array

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

This page provides examples of query operations on array fields using MongoDB Compass. The examples on this page use the inventory collection. Populate the inventory collection with the following documents:

This page provides examples of query operations on array fields using the pymongo.collection.Collection.find() method in the PyMongo Python driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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

Tip

The driver provides com.mongodb.client.model.Filters helper methods to facilitate the creation of filter documents. The examples on this page use these methods to create the filter documents.

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

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

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

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

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

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

This page provides examples of query operations on array fields using the MongoDB::Collection::find() method in the MongoDB Perl Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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

This page provides examples of query operations on array fields using the collection.find() method in the MongoDB Scala Driver. The examples on this page use the inventory collection. To populate the inventory collection, run the following:

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 ] }
]);

You can run the operation in the web shell below:

[
  { 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 ] }
]

For instructions on inserting documents in MongoDB Compass, see Insert Documents.

db.inventory.insert_many([
    {"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]}])
collection.insertMany(asList(
        Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
        Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
db.collection('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]}
])
.then(function(result) {
  // process result
})
$insertManyResult = $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],
    ],
]);
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
        Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
        Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
        Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
var documents = new[]
{
    new BsonDocument
    {
        { "item", "journal" },
        { "qty", 25 },
        { "tags", new BsonArray { "blank", "red" } },
        { "dim_cm", new BsonArray { 14, 21 } }
    },
    new BsonDocument
    {
        { "item", "notebook" },
        { "qty", 50 },
        { "tags", new BsonArray { "red", "blank" } },
        { "dim_cm", new BsonArray { 14, 21 } }
    },
    new BsonDocument
    {
        { "item", "paper" },
        { "qty", 100 },
        { "tags", new BsonArray { "red", "blank", "plain" } },
        { "dim_cm", new BsonArray { 14, 21 } }
    },
    new BsonDocument
    {
        { "item", "planner" },
        { "qty", 75 },
        { "tags", new BsonArray { "blank", "red" } },
        { "dim_cm", new BsonArray { 22.85, 30 } }
    },
    new BsonDocument
    {
        { "item", "postcard" },
        { "qty", 45 },
        { "tags", new BsonArray { "blue" } },
        { "dim_cm", new BsonArray { 10, 15.25 } }
    }
};
collection.InsertMany(documents);
$db->coll("inventory")->insert_many(
    [
        {
            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 ]
        }
    ]
);
client[:inventory].insert_many([{ 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 ] }
                               ])
collection.insertMany(Seq(
  Document("""{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }"""),
  Document("""{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }"""),
  Document("""{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }"""),
  Document("""{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }"""),
  Document("""{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }""")
)).execute()

Match an Array

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

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

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

To specify equality condition on an array, use the query document eq( <field>, <value>) where <value> is the exact array to match, including the order of the elements.

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

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

To specify equality condition on an array, use the query document eq( <field>, <value>) where <value> is the exact array to match, including the order of the elements.

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

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

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

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

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

To specify equality condition on an array, use the query document equal( <field>, <value> ) where <value> is the exact array to match, including the order of the elements.

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

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

Copy the following filter into the Compass query bar and click Find:

{ tags: ["red", "blank"] }
../../_images/compass-array-match-exact.png
cursor = db.inventory.find({"tags": ["red", "blank"]})
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
var cursor = db.collection('inventory').find({ 
  tags: [ "red", "blank" ]
});
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))

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

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

Copy the following filter into the Compass query bar and click Find:

{ tags: { $all: ["red", "blank"] } }
../../_images/compass-array-match-all.png
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
findIterable = collection.find(all("tags", asList("red", "blank")));
var cursor = db.collection('inventory').find({ 
  tags: { $all: [ "red", "blank" ]}
});
$cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);
findPublisher = collection.find(all("tags", asList("red", "blank")));
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => { '$all' => [ "red", "blank" ] } } );
client[:inventory].find(tags: { '$all' => ['red', 'blank'] })
findObservable = collection.find(all("tags", "red", "blank"))

Query an Array for an Element

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

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

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

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

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

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

To query if the array field contains at least one element with the specified value, construct a filter using the Eq method:

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

<value> is the element value to match.

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

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

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

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

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

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

Copy the following filter into the Compass query bar and click Find:

{ tags: "red" }
../../_images/compass-array-elem-match.png
cursor = db.inventory.find({"tags": "red"})
findIterable = collection.find(eq("tags", "red"));
var cursor = db.collection('inventory').find({ 
  tags: "red"
});
$cursor = $db->inventory->find(['tags' => 'red']);
findPublisher = collection.find(eq("tags", "red"));
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => "red" } );
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var builder = Builders<BsonDocument>.Filter;
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 the query filter document:

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

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

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

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

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

For example, the following operation queries for all documents where the array dim_cm contains at least one element whose value is greater than 25.

db.inventory.find( { dim_cm: { $gt: 25 } } )

Copy the following filter into the Compass query bar and click Find:

{ dim_cm: { $gt: 25 } }
../../_images/compass-array-query-op.png
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
findIterable = collection.find(gt("dim_cm", 25));
var cursor = db.collection('inventory').find({ 
  dim_cm: { $gt: 25 }
});
$cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);
findPublisher = collection.find(gt("dim_cm", 25));
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { "dim_cm" => { '$gt' => 25 } } );
client[:inventory].find(dim_cm: { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm", 25))

Specify Multiple Conditions for Array Elements

When specifying compound conditions on array elements, you can specify the query such that either a single array element meets these condition or 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 array contains elements that in some combination satisfy the query conditions; e.g., one element can satisfy the greater than 15 condition and another element can satisfy the less than 20 condition, or a single element can satisfy both:

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

Copy the following filter into the Compass query bar and click Find:

{ dim_cm: { $gt: 15, $lt: 20 } }
../../_images/compass-array-compound-filter.png
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
var cursor = db.collection('inventory').find({ 
  dim_cm: { $gt: 15, $lt: 20 }
});
$cursor = $db->inventory->find([
    'dim_cm' => [
        '$gt' => 15,
        '$lt' => 20,
    ],
]);
findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("dim_cm", 15), builder.Lt("dim_cm", 20));
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { "dim_cm" => { '$gt' => 15, '$lt' => 20 } }
);
client[:inventory].find(dim_cm: { '$gt' => 15,
                                  '$lt' => 20 })
findObservable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))

Query for an Array Element that Meets Multiple Criteria

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

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

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

Copy the following filter into the Compass query bar and click Find:

{ dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }
../../_images/compass-array-compound-multiple-criteria.png
cursor = db.inventory.find(
    {"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
var cursor = db.collection('inventory').find({ 
  dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
});
$cursor = $db->inventory->find([
    'dim_cm' => [
        '$elemMatch' => [
            '$gt' => 22,
            '$lt' => 30,
        ],
    ],
]);
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find(
    { dim_cm => { '$elemMatch' => { '$gt' => 22, '$lt' => 30 } } }
);
client[:inventory].find(dim_cm: { '$elemMatch' => { '$gt' => 22,
                                                    '$lt' => 30 } })
findObservable = collection.find(elemMatch("dim_cm", Document("$gt" -> 22, "$lt" -> 30)))

Query for an Element by the Array Index Position

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

Note

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

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

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

Copy the following filter into the Compass query bar and click Find:

{ "dim_cm.1": { $gt: 25 } }
../../_images/compass-array-match-by-index.png
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
findIterable = collection.find(gt("dim_cm.1", 25));
var cursor = db.collection('inventory').find({ 
  "dim_cm.1": { $gt: 25 }
});
$cursor = $db->inventory->find(['dim_cm.1' => ['$gt' => 25]]);
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { "dim_cm.1" => { '$gt' => 25 } } );
client[:inventory].find('dim_cm.1' => { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm.1", 25))

Query an Array by Array Length

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

db.inventory.find( { "tags": { $size: 3 } } )

Copy the following filter into the Compass query bar and click Find:

{ "tags": { $size: 3 } }
../../_images/compass-array-query-by-size.png
cursor = db.inventory.find({"tags": {"$size": 3}})
findIterable = collection.find(size("tags", 3));
var cursor = db.collection('inventory').find({ 
  tags: { $size: 3 }
});
$cursor = $db->inventory->find(['tags' => ['$size' => 3]]);
findPublisher = collection.find(size("tags", 3));
var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
var result = collection.Find(filter).ToList();
$cursor = $db->coll("inventory")->find( { tags => { '$size' => 3 } } );
client[:inventory].find(tags: { '$size' => 3 })
findObservable = collection.find(size("tags", 3))

Additional Query Tutorials

For additional query examples, see: