Java Programming Tutorials

Java programming tutorials with many code examples!

MongoDB 3 array query operations

MongoDB 3 array query operations are very helpful and simplify digging in nested structures. In this post we’ll show how to create queries that match array elements in various ways.

Test collection with book authors

Let’s use the following collection with authors stored in arrays:

db.books.find().pretty()
{ "_id" : 1, "authors" : [ "Joyce", "Dante" ] }
{ "_id" : 2, "authors" : [ "Tolstoy", "Joyce" ] }
{ "_id" : 3, "authors" : [ "Dante", "Joyce" ] }

Documents with only these authors in the same order (the same array)

Console version

db.books.find({authors: ["Joyce", "Dante"]})

{ "_id" : 1, "authors" : [ "Joyce", "Dante" ] }

Java version

// this code is uncool, but works:
BsonArray values = new BsonArray();
values.add(new BsonString("Joyce"));
values.add(new BsonString("Dante"));
books.find(Filters.eq("authors", values));

Any document with Joyce among authors

Console version

db.books.find({authors: "Joyce"})

{ "_id" : 1, "authors" : [ "Joyce", "Dante" ] }
{ "_id" : 2, "authors" : [ "Tolstoy", "Joyce" ] }
{ "_id" : 3, "authors" : [ "Dante", "Joyce" ] }

Java version

books.find(Filters.eq("authors", "Joyce"))

Any document with these two authors in any order in the array

Console version

db.books.find({authors: {$all: ["Joyce", "Dante"]}})

{ "_id" : 1, "authors" : [ "Joyce", "Dante" ] }
{ "_id" : 3, "authors" : [ "Dante", "Joyce" ] }

Java version

// all(field name, value1, value2, ...)
books.find(Filters.all("authors", "Joyce", "Dante"));

Find on specific position in an array:

Console version

db.books.find({"authors.0": "Joyce"}) // 1
{ "_id" : 1, "authors" : [ "Joyce", "Dante" ] }

db.books.find({"authors.1": "Joyce"}) // 2, 3
{ "_id" : 2, "authors" : [ "Tolstoy", "Joyce" ] }
{ "_id" : 3, "authors" : [ "Dante", "Joyce" ] }

Java version

books.find(Filters.eq("authors.0", "Joyce"));
books.find(Filters.eq("authors.1", "Joyce"));
Share with the World!