【问题标题】:Find by reference field按参考字段查找
【发布时间】:2016-10-20 12:41:31
【问题描述】:

我有两个系列:City 和 Country。在 City 中,我有一个字段 country,它是对 Country 集合的引用。

所以我尝试查找为:

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

但这会返回空数组。如果我使用不带表达式的查找,那么这会返回所有结果,包括“美国”。

【问题讨论】:

  • 请发布您的国家和城市集合的数据结构

标签: mongodb mongodb-query


【解决方案1】:

考虑在聚合框架中使用 $lookup 运算符,该运算符对同一数据库中的另一个集合执行左外连接,以过滤来自“已连接”集合的文档进行处理:

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

【讨论】:

    【解决方案2】:

    假设您通过城市集合中的 ID 引用国家/地区,我认为您必须递归执行此操作。这可能是一个可能的解决方案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多