首页 > 解决方案 > MongoDB:如何对嵌套位置属性执行空间查询?

问题描述

我有这样的文档结构:

{
    name: "John",
    addresses: [
        {
            city: "London",
            location: {
                type: "Point",
                coordinates: [0, 0]
            }
        },
        {
            city: "New York",
            location: {
                type: "Point",
                coordinates: [-74, 40]
            }
        }
    ]
},
{
    name: "Joanna",
    addresses: [
        // Similar array of her addresses
    ]
}

现在,我有一个坐标x = (0.0001, 0.0001)。我想获取我的收藏中所有地址接近这一点的人,并且只获取响应中的那些地址。对于查询坐标 as x,我只想要 John 在响应中的第一个地址:

{
    name: "John",
    addresses: [
        {
            city: "London",
            location: {
                type: "Point",
                coordinates: [0, 0]
            }
        }
    ]
}

我见过类似的例子,但它们都返回整个文档,即它们会返回 John 的所有地址。如何只返回查询坐标附近的地址(可能不止一个,因此操作员将无法工作) ?$x

PS - 我确实尝试过展开然后检查(使用聚合框架),但这不允许我在除了管道的第一阶段之外的任何其他地方使用空间查询。

标签: mongodbmongodb-queryaggregation-framework

解决方案


首先,您应该检查存在多少个地址。然后,如果超过 0,您可以使用 slice 方法。如果地址数组长度为零,则返回 null。

db.collection.aggregate([
{
    {$addFields: {'addressCount': {$size: '$addresses'}}},
    {$addFields: {'firstAddress': {
        $cond: {
            if: { $gt: ['$addressCount', 0]},
            then: { "$slice" : [ "$addresses" , 0, 1 ] },
            else: null
        }}
    }},
    "$project": {
        "name": 1,
        "firstAddress" : 1
    }
}
])

推荐阅读