Cristi
Cristi

Reputation: 1338

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

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.

Upvotes: 1

Views: 672

Answers (3)

Haruo
Haruo

Reputation: 516

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.

Upvotes: 0

prasad_
prasad_

Reputation: 14317

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

Upvotes: 1

Pritam Jana
Pritam Jana

Reputation: 296

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

Upvotes: 0

Related Questions