How to express a query to match elements of a subdocument?

110 views
Skip to first unread message

Russell Bateman

unread,
Aug 18, 2012, 12:12:15 PM8/18/12
to mongodb-user

I have a representative collection to illustrate what I want to be able to match, that is, a subdocument within a larger document containing a random list of tuples (fieldname "data" below) a subset of which I want to match (i.e.: $eq, if that were possible) to cause the (whole) document to be returned from the query.

> db.tuples.findOne();
{
    "_id" : ObjectId("502fb6a9674c381db9e9249a"),
    "rats" : "very large mice",
    "x" : 1,
    "data" : {
        "this" : "uh-huh",
        "that" : "oh-oh",
        "other" : "poo-poo-pee-doo"
    }
}

I'm not trying to get back just the subdocument or anything weird like that, I want the whole document back when one or more tuples I specify match exactly in the subdocument.

Stabbing around, I find nothing working from what I know how to express: I haven't hit upon the right query yet. Googling for examples has so far not turned anything up. The favorite examples that come close always appear to be arrays and not "subdocuments". The array thing just doesn't work.

Two examples so far about which Mongo hasn't complained are below, but they do not match.

> db.tuples.find( { "data" : { "this":"uh-huh", "that":"oh-oh" } } );
> db.tuples.find( { $and : [ { "data" : { "this":"uh-huh" } }, { "data" : { "that":"oh-oh" } } ] } );


Profuse thanks for any help, direction, nudges, etc.,

Russ Bateman

Reno Reckling

unread,
Aug 18, 2012, 12:13:27 PM8/18/12
to mongod...@googlegroups.com
On 08/18/2012 06:12 PM, Russell Bateman wrote:>
> Two examples so far about which Mongo hasn't complained are below, but they do not match.
>
> > db.tuples.find( { "data" : { "this":"uh-huh", "that":"oh-oh" } } );
> > db.tuples.find( { $and : [ { "data" : { "this":"uh-huh" } }, { "data" : { "that":"oh-oh" } }
] } );
>
>
> Profuse thanks for any help, direction, nudges, etc.,
>

Hi,
try
db.tuples.find( { "data.this":"uh-huh", "data.that":"oh-oh"} );
db.tuples.find( { $and : [ { "data.this":"uh-huh" }, { "data.that":"oh-oh" } ] } );

Regards,
Reno

Russell Bateman

unread,
Aug 18, 2012, 12:19:50 PM8/18/12
to mongod...@googlegroups.com
Ooh, thanks for the quick reply. Yes, it works. I'm always so thrown off
by the dotted notation thing. This experience just may clench it for me.

Many thanks!
Reply all
Reply to author
Forward
0 new messages