【问题标题】:Mongoose - constructing an AND queryMongoose - 构建 AND 查询
【发布时间】:2014-11-11 11:24:30
【问题描述】:

我有以下执行 GEO 多边形搜索的 Mongoose 查询:

Location.find({
    "location.coordinates": {
        "$geoWithin": {
            "$geometry": {
                "type": "Polygon",
                "coordinates": [
                    coords
                ]
            }
        }
    }
}, cb);

我现在希望限制包含“评级”属性 = 5 的搜索结果,因此有效地使用 AND,即地理搜索 AND 评级为 5。

谁能告诉我如何构建查询以结合 GEO 搜索和评级属性?

【问题讨论】:

  • 默认情况下,MongoDB 中的所有查询都是隐含的“与”语句。有一个 $and 运算符,但它通常只用于“相同”字段的多个条件或更复杂的嵌套。您应该能够添加条件。您是否真的质疑“这如何与地理定位一起工作?”
  • @NeilLunn - 非常感谢 - 我是 Mongo 的新手,所以按照您的建议添加条件是理想的。

标签: node.js mongodb mongoose


【解决方案1】:

假设评级字段位于文档的顶层,我相信以下内容可以实现您想要的效果

Location.find({
"$and" : [      
         {"location.coordinates": {
          "$geoWithin": {
           "$geometry": { "type": "Polygon","coordinates": [coords] } }
           }
         },
         {"ratings" : 5}
         ]

}, cb);

【讨论】:

  • 非常不必要,因为只需在 .find() 的顶层添加“评级”字段即可。默认情况下,MongoDB 中的所有查询参数都是“与”操作。
  • 非常有必要,因为我对他的架构知之甚少,鉴于缺乏其他信息,这是我能提供的最安全的答案。显然 javascript 不允许重复键,所以“$and”实际上只需要在同一字段上表示多个运算符。
【解决方案2】:

感谢@NeilLunn 和@bearrito 的指导。我可以简单地将条件作为父条件:

    Location.find({
    "rating": 5,
    "location.coordinates": {
        "$geoWithin": {
            "$geometry": {
                "type": "Polygon",
                "coordinates": [
                    coords
                ]
            }
        }
    }
},cb)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2013-06-15
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2017-01-14
    相关资源
    最近更新 更多