MongoDB条件投影

8

我希望有条件地在响应中省略字段。

我有一个聚合查询,使用geoNear查找最近的POI,如果查询点与POI之间的距离小于500,则只想检索所有信息。

假设我希望在距离小于或等于500的情况下省略“someField”。

以下是我的解决方案:

db.pois.aggregate([
    { 
        "$geoNear": {
        "near": {
                type: "Point", 
                coordinates: [49.607857, 6.129143]
        }, 
        "maxDistance": 0.5 * 1000,
        "spherical": true,
        "distanceField": "distance"
        }
    }, {
        $project: {
            _id:0,
            "someField": {
                $cond: [{$lte: ["$distance", 500]}, 1, 0 ]
            }
        }
    } 
]).pretty()

但是,这个查询并没有将"distance"字段从响应中省略掉,而是以某种方式将其替换为0或1的值。非常感谢您的帮助。
1个回答

17

从MongoDB 3.6开始,您可以在聚合表达式中使用变量REMOVE来有条件地禁止一个字段。

$$REMOVE

查询:

db.pois
  .aggregate([
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: [49.607857, 6.129143]
        },
        maxDistance: 0.5 * 1000,
        spherical: true,
        distanceField: "distance"
      }
    },
    {
      $project: {
        _id: 0,
        someField: {
          $cond: {
            if: { $lte: ["$distance", 500] },
            then: "$$REMOVE",
            else: "$distance"
          }
        }
      }
    }
  ])
  .pretty();

3
谢谢,我刚在你发布的第二条内容中找到了答案。我本应该好好阅读文档的。谢谢 :) - LostSoul
1
这是一个写得很好的解决方案。谢谢你,我很感激你的努力。你让我的一天变得更美好了。 - damisparks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接