我有一个嵌套的对象。集合中的每个文档如下所示:
{
anything: "whatever",
something: {
// find inside of these document
a: { getThis: "wow" },
b: { getThis: "just wow" },
c: { getThis: "another wow" }
}
}
我想在something
中的每个文档的每个getThis
中find
。
例如,我想查找具有getThis: "wow"
的文档。
我试着在*
:中使用类似通配符的东西
{"something.*.getThis": "wow" }
我也尝试过$elemMatch
,但它似乎只适用于array
;
{ something: { $elemMatch: { getThis: "wow" } } }
您可以尝试使用$objectToArray
、
$addFields
将something
转换为somethingArr
中的数组$match
条件getThis
是否为wow
$project
删除somethingArr
db.collection.aggregate([
{
$addFields: {
somethingArr: { $objectToArray: "$something" }
}
},
{ $match: { "somethingArr.v.getThis": "wow" } },
{ $project: { somethingArr: 0 } }
])
游乐场
第二种可能的方式
$filter
输入something
作为数组,使用$objectToArray
进行转换- 过滤器将检查条件
getThis
是否等于wow
db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
[],
{
$filter: {
input: { $objectToArray: "$something" },
cond: { $eq: ["$$this.v.getThis", "wow"] }
}
}
]
}
}
}
])
游乐场