如何在不知道父字段的情况下在Mongo中查找子字段? [英] How to find a subfield in Mongo without knowing the parent field?

查看:60
本文介绍了如何在不知道父字段的情况下在Mongo中查找子字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下集合:

db.test.insertMany([
    {"_id": 1, "Jimmy": {"Loved by mom": true}},
    {"_id": 2, "Andrew": {"Loved by mom": false}},
    {"_id": 3, "Nicholas": {"Loved by mom": true}}",
    {"_id": 4, "Sarah": {"Loved by dad": true}}
]);

是否有一种方法可以搜索具有子字段"Loved by mom"的所有文档,而又不知道父字段是什么?为了(希望)简化此任务,所需子字段始终位于深度1.

Is there a way to search for all documents that have the subfield "Loved by mom", without knowing what the parent field is called? To (hopefully) simplify this task, the desired subfield is always located at depth 1.

推荐答案

是否可以搜索具有子字段的所有文档 被妈妈爱",却不知道父域是什么?

Is there a way to search for all documents that have the subfield "Loved by mom", without knowing what the parent field is called?

此聚合查询可以做到这一点:

This Aggregation query can do that:

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 } }
] )

这篇关于如何在不知道父字段的情况下在Mongo中查找子字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆