我在 mongodb 上有这些类型的项目:
{
"_id": { "$oid" : "2" },
"waypoints": [
{
"step": 0,
"coordinates": [1,2]
},
{
"step": 1,
"coordinates": [1,3]
},
{
"step": 2,
"coordinates": [1,4]
}
]
}
我尝试在集合中查找 [1,2] 来检索 waypoints.step 和 _id,但结果不是我所期望的。
我想要得到:
{
"_id": { "$oid" : "2" },
"waypoints": [
{
"step": 0
}
]
}
但我得到:
{
"_id": { "$oid" : "2" },
"waypoints": [
{
"step": 0,
},
{
"step": 1,
},
{
"step": 2,
}
]
}
实现我想要的目的的正确查询是什么?
我只知道坐标,我需要检索对象的 _id 以及与我要查找的坐标相对应的步骤。
谢谢
最佳答案
您可以通过投影数据来做到这一点。查询应该是:
db.collection.find({"_id": { "$oid" : "2" }},{waypoints : {$elemMatch : {coordinates:[1,2]}}})
欲了解更多信息,请查看$elemMatch运算符。
关于node.js - Mongodb,在嵌套数组中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21047314/