Home > Software design >  Querying mongodb for a nested object
Querying mongodb for a nested object

Time:02-21

I have Book objects in my mongoDb that look like this (very simplified):

{
  "_id": ObjectId("620e341dbf575892d9396dc2"),
  "title": "my title",
  "author": {
    "_id": ObjectId("620e341dbf575892d9396dd4"),
    "surname": "My surname"
  }
}

I'm trying to query and get all books by an author, and so far I've tried:

const booksByAuthor = await Book.find({ author: { _id: "620e341dbf575892d9396dd4" } });

and

const booksByAuthor = await Book.find({ 'author._id': "620e341dbf575892d9396dd4" } );

But in no case I'm getting the existing books from the given author, and I'm only getting empty arrays.

What am I doing wrong?

CodePudding user response:

The problem for 1st query:

When you want to query in a nested field you have to use dot notation as you do in the second query.
The problem to not use dot notation is mongo match the entire object (even the fields order) so is not a good way... you can check simple examples like:

  • This one: The object is found because the object is exactly the same.
  • Another this one where the object has the same fields and values from two objects in the collection but... querying using an object the order matters, so only returns one.

The problem for 2nd query:

I think the problem here is you are matching string vs ObjectId. The syntaxis is correct (dot notation) but when mondo match the values one of them is string and another is ObjectId.

So you can try this query:

const booksByAuthor = await Book.find({ 'author._id': mongoose.Types.ObjectId("620e341dbf575892d9396dd4") } );

Check this example with your query, matching string and ObjectId none result is returned, but parsing string to ObjectId... magic appears

  • Related