1

Having this structure:

/* 0 */
{
    "_id" : ObjectId("53f1f19a477aa5da607b20a4"),
    "name" : "Anna"
}

/* 1 */
{
    "_id" : ObjectId("53f1f192477aa5da607b20a3"),
    "name" : "Josh",
    "mother" : ObjectId("53f1f19a477aa5da607b20a4")
}

Is it possible get the complete document of mother instead get the ObjectId. I mean, if i do this query: db.tree.find({"name" : "Josh"}) i get the document of Josh, but i am not able to get the name of Anna because i should do another query. It's possible in mongodb get the complete tree/json of the documents when one of the field is refering to another document to avoid multiple queries?

Community
  • 1
  • 1
Enzo
  • 4,111
  • 4
  • 21
  • 33

2 Answers2

1

It depends on which driver you are using but you can use a DBref. Take a look at this article

Your "Josh" object would look like this: { "_id" : ObjectId("53f1f192477aa5da607b20a3"), "name" : "Josh", "mother" : { "$ref" : "tree", "$id": ObjectId("53f1f19a477aa5da607b20a4") } }

If you use Java and Spring's MongoTemplate, you can do that by using the annotation @DBRef and when you query for Josh you'll get Anna embedded in Josh's object

AntonioOtero
  • 1,759
  • 1
  • 14
  • 16
1

For clarity: MongoDB does not do joins - resolving the mother ObjectId into a document requires a second query. As AntonioOtero pointed out, some drivers and ORMs, like MongoTemplate or Mongoose, will do the reference resolution for you, automatically or by request. You should be aware that this results in multiple database queries, however.

wdberkeley
  • 11,531
  • 1
  • 28
  • 23