【问题标题】:Where condition as variable in resultswhere 条件作为结果中的变量
【发布时间】:2015-06-11 21:42:29
【问题描述】:

现在我有这个使用地理空间数据的 Moongose 查询:

Locations.find({
    loc: {
        $geoWithin: {
            $centerSphere: [[lng, lat], radius / 6378.1],
        },
    }
}, cb);

效果很好,但我的问题是如何获取所有 Location 文档,其中每个文档都有一个布尔变量,显示该特定文档是否在 where 子句的指定圆圈内。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您可以使用聚合$project 阶段执行类似的操作,将条件投影为结果文档中的附加字段。不幸的是,没有为聚合框架定义 GeoSpatial 运算符,因此您无法在单个 MongoDB 查询中实现目标。

    如果您可以进行两次查询,您可以尝试以下选项:

    db.locations.aggregate([
        {$match: {
                    loc: {
                            $geoWithin: {
                                           $centerSphere: [[lng, lat], radius / 6378.1],
                                        },
                         }
                  }
         },
         {$project: 
                     {
                         ...
                         // all of your fields
                         ...
                         isWithin: true
                     }
         }                  
    ])
    

    然后反过来做同样的事情,匹配不在其中的文档,并将isWithin设置为false。这会人为地得到你想要的结果。

    【讨论】:

    • 感谢您的回复。你说的反转是什么意思?我试过你的代码,但isWithinundefined
    猜你喜欢
    • 2019-06-14
    • 2017-04-25
    • 1970-01-01
    • 2018-12-23
    • 2021-04-01
    • 1970-01-01
    • 2011-10-30
    • 2016-02-15
    • 1970-01-01
    相关资源
    最近更新 更多