MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come trovare un sottocampo in Mongo senza conoscere il campo padre?

Questa query di aggregazione può farlo:

var loved_by_mom = "Loved by mom";

db.loved.aggregate( [
        { $addFields: { fieldNameValues: { $objectToArray: "$$ROOT" } } },
        { $unwind: "$fieldNameValues" },
        { $addFields: { fldType: { $type: "$fieldNameValues.v" } } },
        { $match: { fldType: "object" } },
        { $addFields: { objs: { $objectToArray: "$fieldNameValues.v" } } },
        { $unwind: "$objs" },
        { $match: { "objs.k": loved_by_mom } }, 
        { $project: { fieldNameValues: 0, fldType: 0, objs: 0 } }
] )