Paul
Paul

Reputation: 33

MongoDB: nested search in list of DBREFs

I'm in front of a Mongo DB that uses lists of nested DBREFs. (Yes, i know that's a very strange way to use Mongo, and beside this, it would be better not to use the @DBREF)

We have collections of readers, books and authors.

The reader looks like this:

{
    "_id" : ObjectId("12345"),
    "age" : 37,
    "books" : [ 
        {
            "$ref" : "book",
            "$id" : "123"
        }, 
        {
            "$ref" : "book",
            "$id" : "456"
        }
    ]
}

The $ref contains the collection name, the $id the id of the book.

Obviously, the books look the same way; instead of a list of books DBREFs, they have a list of authors DBREFs.

Two questions:

  1. Is there a way to list the readers with books of author1 in their list?
  2. How can I list the readers that have only books of authors less than 40 years?

Trying to solve this with Java...

Upvotes: 2

Views: 644

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34581

To query based on database references with the Java driver, use the class DBRef.

1. Is there a way to list the readers with books of author1 in their list?

Yes. Get all book IDs of author1 with a separate query and then find all readers that have a book reference $in your list of book IDs.

2. How can I list the readers that have only books of authors less than 40 years?

This time, you'll need three queries:

  1. Find the IDs of all authors younger than 40
  2. Find all books that have an author with ID $in your list from step 1.
  3. Find all readers that have a book with ID $in your list from step 2.

This may be quite heavy, but that's what you get for storing data in a normalized way in a database that does not support joins. Another approach would be to restructure your data in a way that will simplify your queries.

Upvotes: 1

Related Questions