【问题标题】:Complex query on mongodb data对mongodb数据的复杂查询
【发布时间】:2015-12-15 17:53:29
【问题描述】:

我在mongodb中有以下数据:

[
{
_id: '1',
  address: "64th St and 5th Ave, New York, NY 10021, United States",
  location: {
    lat: 40,
    lng: -73
  }
},
{
_id: '2',
  address: "108 Cobb Avenue, Elmsford, NY, Estados Unidos",
  location: {
    lat: 40,
    lng: 65
  }
},
{
_id: '3',
  address: "78 Cobb Avenue, Elmsford, NY, Estados Unidos",
  location: {
    lat: 41,
    lng: -73
  }
}
]

我还需要在集合中搜索以下位置数组:

[
  {latitude: 40, longitude: -73},
{latitude: 55, longitude: -73},

  ]

我希望查询仅找到具有 _id '1' 的项目,因为它与搜索条件中同一元素的纬度和经度匹配。
我最初考虑使用 $in 但我需要匹配数组中的两个字段,也考虑过 $elemMatch,但我不确定这如何适合。我考虑将搜索的纬度和经度拆分为两个单独的数组和在两者上都使用 $in 但我可能会匹配仅适合单独查询位置中的一对的元素(因为不能保证匹配将位于相同的数组位置)。

任何人都知道如何构建此查询而不使用 hack,例如添加第三个字段,它是两者的连接并使用 $in 搜索它?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    $in 工作得很好。只需确保字段(latlng)的名称与您的数据中的名称相同,并且它们以完全相同的顺序列出。 $in 将检查整个 location 文档是否对应于传递数组中的至少一个文档。

    db.locations.find({
        location: {
            $in: [
                { lat: 40, lng: -73 },
                { lat: 55, lng: -73 }
            ]
        }
    })
    

    【讨论】:

    • @TheZuck 欢迎您。那么它对你有用吗?
    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2023-04-11
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多