简体   繁体   中英

mongodb java driver. How to return object by reference

For example, i have two collections "animals" and "food". In collection "animals" there is a field food, which is reference to collection "food" (not embedded). Im using mongo java driver:

    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);

it return name and Id of object "food". So what would be the proper way to get fields of object "food"?

The short answer is that you can't do that sort of thing automatically in MongoDB. It does not have the concept of a 'join'. You'll just have to make a separate query.

This section of the documentation on Database Reference should help clarify.

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.

Oftentimes, its best to store things as embedded documents, especially if you would have to 'manually join' those documents often. Just depends on your data and how you need to query it. YMMV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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