Find by reference field

时间:2016-10-20 12:41:32

标签: mongodb mongodb-query

I have two collections: City and Country. In City I have a field country, which is a reference to the Country collection.

So I tried find as:

db.city.find( { country.name: "USA" } )

but this return empty array. If I use find without expression then this return me all results, also with "USA".

2 个答案:

答案 0 :(得分:0)

Assuming that you reference to the country via its ID in the city collection, I think that you have to do this recursively. This may be a possible solution:

db.country.find({ name: "USA" }, function(err, country) {
  db.city.find({ country: country.id }, function(err, cities) {
    // do something with the data...
  });
});

答案 1 :(得分:0)

Consider using the $lookup operator in the aggregation framework which performs a left outer join to another collection in the same database to filter in documents from the "joined" collection for processing:

db.city.aggregate([
    {
        "$lookup": {
            "from": "country",
            "localField": "country",
            "foreignField": "_id", // <-- reference field from country collection
            "as": "resultingArray"
        }
    },
    { "$match": { "resultingArray.name": "USA" } }
])