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)。我想让我的收藏中的所有人都在此点接近这个点,并且仅在响应中获得这些地址。对于查询坐标为x,我只想在响应中约翰的第一个地址:

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

我已经看到了类似的例子,但是它们都返回了整个文档,即他们返回了约翰的所有地址。我如何仅返回地址(可能有多个,因此$操作员无法正常工作(,它们在查询坐标 x

附近

P.S。 - 我确实尝试了放松然后检查(使用聚合框架(,但这不允许我在其他任何地方使用空间查询。

首先,您应该检查存在多少个地址。然后,如果超过0,则可以使用切片方法。如果地址数组长度为零,则返回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
    }
}
])

最新更新