How to find a subfield in Mongo without knowing the parent field?

我们两清 提交于 2019-12-24 06:29:48

问题


Given the following collection:

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

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.


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



回答2:


string $search from $text, This query returns the documents that contain the term Loved by mom in the indexed subject field, or more precisely, the stemmed version of the word:

db.test.find( { $text: { $search: "Loved by mom" } } )



回答3:


I don't know an easy way to do what you want.

In your case I would change the way your documents are inserted into MongoDB:

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

Then you could make the query like this:

db.test.find({"lovedBy.mom" : {$exists: true}});

It is important to always have a document structure that allows you to query information in a simpler way.

Although MongoDB allows you to have a flexible structure, I would not recommend using documents that have unique fields for each document.

It would not make sense for each document to have a unique field and you want to search for the child fields of those unique fields.

This way you would only be hindering your work.



来源:https://stackoverflow.com/questions/58642944/how-to-find-a-subfield-in-mongo-without-knowing-the-parent-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!