简体   繁体   English

直接在mongodb中通过ObjectID获取子文档

[英]Getting subdocument by ObjectID directly in mongodb

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 . 是否有可能获得母亲的完整文件而不是获得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. 我的意思是,如果我执行以下查询: db.tree.find({"name" : "Josh"})我得到了Josh的文档,但是我无法获得Anna的名称,因为我应该再进行一次查询。 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? 当一个字段引用另一个文档以避免多个查询时,mongodb中有可能获取文档的完整树/ json吗?

It depends on which driver you are using but you can use a DBref. 这取决于您使用的驱动程序,但可以使用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") } } 您的“ Josh”对象如下所示: { "_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 如果您使用Java和Spring的MongoTemplate,则可以使用批注@DBRef来实现,当您查询Josh时,Anna会嵌入到Josh的对象中

For clarity: MongoDB does not do joins - resolving the mother ObjectId into a document requires a second query. 为了清楚起见:MongoDB不执行联接-将mother ObjectId解析为文档需要第二次查询。 As AntonioOtero pointed out, some drivers and ORMs, like MongoTemplate or Mongoose, will do the reference resolution for you, automatically or by request. 正如AntonioOtero指出的那样,某些驱动程序和ORM(例如MongoTemplate或Mongoose)将自动或通过请求为您完成参考解析。 You should be aware that this results in multiple database queries, however. 您应该知道,这会导致多个数据库查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM