mongodb - 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 - 我确实尝试过展开然后检查(使用聚合框架),但这不允许我在除了管道的第一阶段之外的任何其他地方使用空间查询。
解决方案
首先,您应该检查存在多少个地址。然后,如果超过 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
}
}
])
推荐阅读
- javascript - How to get the array value from axios response
- python - SQLAlchemy - 在整个数据库模型列中搜索模式
- asp.net-web-api - CORS 在 IIS Express 中运行良好,但在 IIS 中失败
- postman - 我如何在邮递员中获取 Amazon Cognito 令牌而无需手动步骤
- java - 如何通过 REST API 关联两个实体
- c++ - 为什么在接受输入后循环退出时不会这样做
- reactjs - React-Redux 更新和重定向逻辑
- c++ - 在 GCC 上无法编译 std::tuple 与多个空成员的比较
- javascript - vue.js:`vue create` 在项目文件夹中仅创建 3 个文件(package.json、package-lock.json、README.md)
- android - 获取唯一的设备 ID