gpt4 book ai didi

java - mongodb java 驱动程序。如何通过引用返回对象

转载 作者:太空宇宙 更新时间:2023-11-04 14:26:09 25 4
gpt4 key购买 nike

例如,我有两个集合“动物”和“食物”。在“动物”集合中,有一种野外食物,它引用了“食物”集合(未嵌入)。我使用 mongo java 驱动程序:

    DBCollection collection = db.getCollection("animals");
DBObject fields = new BasicDBObject("name", 1);
fields.put("food", 1);
fields.put("_id", 0);
DBObject project = new BasicDBObject("$project", fields );
collection.aggregate(project);

它返回对象“food”的名称和ID。那么获取对象“食物”字段的正确方法是什么?

最佳答案

简短的回答是,您无法在 MongoDB 中自动执行此类操作。它没有“连接”的概念。您只需进行单独的查询即可。

此部分documentation on Database Reference应该有助于澄清。

To resolve DBRefs, your application must perform additional queries to return the referenced documents. Many drivers have helper methods that form the query for the DBRef automatically. The drivers [1] do not automatically resolve DBRefs into documents. DBRefs provide a common format and type to represent relationships among documents. The DBRef format also provides common semantics for representing links between documents if your database must interact with multiple frameworks and tools.

通常,最好将内容存储为嵌入式文档,特别是当您必须经常“手动加入”这些文档时。仅取决于您的数据以及您需要如何查询它。 YMMV

关于java - mongodb java 驱动程序。如何通过引用返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com