mongodb - mongodb查询中键的通配符
问题描述
我有一个相当于:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"sides": {
"0": {
"dist": 100
},
"1": {
"dist": 10
}
}
},
{
"_id": ObjectId("5a934e000102030405000001"),
"sides": {
"0": {
"dist": 100
}
}
}
]
我想执行一个查询,该查询返回任何嵌套的任何键的文档都具有具有特定值sides
的键。dist
就像是:
db.collection.find({"sides.*.dist": 10})
这里*
充当通配符,任何键都可以代替它。
那将检索:
[
{
"_id": ObjectId("5a934e000102030405000000"),
"sides": {
"0": {
"dist": 100
},
"1": {
"dist": 10
}
}
}
]
另一方面
db.collection.find({"sides.*.dist": 100})
将检索两个文件。
解决方案
您可以使用此获取匹配元素
db.collection.aggregate([
{
"$project": {
"sides_array": {//Reshape the sides
"$objectToArray": "$sides"
}
}
},
{//Denormalize to get more than one matches
"$unwind": "$sides_array"
},
{
"$match": {//Condition goes here
"sides_array.v.dist": 10
}
},
{
"$group": {//Group the data back, after unwinding
"_id": "$_id",
"sides": {
"$push": "$sides_array"
}
}
},
{
"$project": {//Reshape the data
"_id": 1,
"sides": {
"$arrayToObject": "$sides"
}
}
}
])
推荐阅读
- python - Alpine 3.9 强制使用 python 3.6
- neural-network - 如何只训练神经网络的前部?
- c# - Linq.Any() 总是遍历整个列表还是会在找到第一个匹配项时退出?
- android - AVD 未运行,需要 Intel HAXM
- sql - SQL - 返回仅将项目评论为“差”的用户 ID
- java - 记录实际的存储库类而不是 JPARepository 的 CrudRepository
- c++ - C++中类对象属性的内存管理
- php - 组合 $request->request 和 $request->files 数组
- php - php array_diff 不适用于此比较
- html - 当数据很多时,如何将 chromes devtools 保存为 html?