redexp
redexp

Reputation: 5065

Mongo: find subdocument without dot notation

For example we have collection

{field: {subfield: 'name'}}
{field: {subfield: 'phone'}}

Can I find document without dot notation? Like this

db.test.find({field: {subfield: /regex/}})

or maybe like this

db.test.find({field: {$someOperator: {subfield: /regex/}}})

I just don't want to build dot notation like

db.test.find({"field.subfield": /regex/})

Upvotes: 8

Views: 3882

Answers (2)

Ethan
Ethan

Reputation: 141

Yes, this is possible using an aggregation pipeline.

First, use $replaceRoot to move the root document to the subdocument. Also, retain the root document ($$ROOT) in a field so that you can output it later.

$replaceRoot: {
    newRoot: {
        $mergeObjects: [{
                _root: "$$ROOT"
            },
            "$field"
        ]
    }
}

Next, use $match to perform your query on the subdocument.

$match: {
    subfield: /regex/
}

Finally, use $replaceRoot to set the root back to the whole document.

$replaceRoot: {
    newRoot: "$_root"
}

I don't think this would be very performant, but it works.

Upvotes: 0

Sammaye
Sammaye

Reputation: 43884

The problem is that:

db.test.find({field: {$someOperator: {subfield: /regex/}}})

Is actually another way of querying in MongoDB which uses object euqality to search for subdocuments.

So no, you must use dot notation unless you were searching for where one object exactly equals the other.

That being said you could wrap the document in $elemMatch: http://docs.mongodb.org/manual/reference/operator/elemMatch/ that would work

Edit

Considering you collection structure $elemMatch won't actually work.

Upvotes: 5

Related Questions