I have a mongo document that looks like the below JSON object. What I’m trying to do, using the mongoDb Query builder, is return all books from user 1 that are read: false.
For example:
var query = new Query();
query.addCriteria(Criteria.where("id").is(1));
query.fields().elemMatch("books", Criteria.where("read").is(false));
return users 1 and the first unread book but i’d like the full list of unread box.
Users:[
{
id: 1,
name: 'John Doe',
books: [
{
id: 1,
title: 'The Hobbit',
read: false
},
{
id: 2,
title: 'The Lord of the Rings',
read: false
},
{
id: 3,
title: 'The Silmarillion',
read: false
}
]
},
{
id: 2,
name: 'Jane Doe',
books: []
}
}
2
Answers
Here is a solution using a MongoRepository<Users,Long> Interface and @Aggregation pipeline. Cleaner then the query builder IMO and supports searching and paging.
BookList class
You can use filter with project stage in an aggregation pipeline.
Mongo Playground
The query translates to this project stage of the pipeline.