如何使用find查找MongoDB中对象的嵌套对象



我有一个嵌套的对象。集合中的每个文档如下所示:

{
anything: "whatever",
something: {
// find inside of these document
a: { getThis: "wow" },
b: { getThis: "just wow" },
c: { getThis: "another wow" }
}
}

我想在something中的每个文档的每个getThisfind


例如,我想查找具有getThis: "wow"的文档。

我试着在*:中使用类似通配符的东西

{"something.*.getThis": "wow" }

我也尝试过$elemMatch,但它似乎只适用于array

{ something: { $elemMatch: { getThis: "wow" } } }

您可以尝试使用$objectToArray

  • $addFieldssomething转换为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"] }
}
}
]
}
}
}
])

游乐场