Search code examples
mongodbdbref

Difference between embedded and dbRef fields while building search query in MongoDB


Here I have the object having two fields, one is embedded and the other is DbRef in mongoDB collection.

Suppose the object have the embedded field named product and the DbRef field named company.

If I want to search the object having the value "ABC" of the id in the product object. Then the criteria that would be used to search is:

Criteria criteria = Criteria.where("product.id")
    .is("ABC");

Now if I want to search the object having both product.id as "ABC" as well as having company.name as "XYZ" what would be my criteria.

Would there be any difference in query due to company being DbRef field?


Solution

  • A DbRef is not automatically dereferenced by the MongoDB node, you would either need to:

    • find all documents with the matching product.id, then use then use a client-side function like mongoose's populate to fill in the referenced data, and match the company.name on the client side
    • use aggregate with $lookup to explicitly populate the reference field on the server side, and then $match the company.name