Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I query with elemMatch in mongoose?

I'm trying to query a user in my mongodb collection based on the following mongodb query:

db.users.find("boxes":{"$elemMatch":{"a":"foo","b":"bar"}})

This works if I query directly with mongodb. It returns any user that has a box with a="foo" and b="bar".

How can I query this in mongoosejs? I've tried using User.find().elemMatch but it doesn't work. That seems like its just projecting the results anyway. The original mongodb query does work for me though, I just need to be able to replicate it in mongoosejs. Any ideas?

like image 444
brandon Avatar asked Mar 12 '14 17:03

brandon


3 Answers

Documentation for elemMatch in mongoose is here.
I've not tested it, but it looks like you'll want to do

User.find().elemMatch("boxes", {"a":"foo","b":"bar"})

like image 193
Tim Brown Avatar answered Oct 06 '22 20:10

Tim Brown


Tim's answer is correct, but if anyone runs into confusion with what mongoose generates for queries on the mongo native API, I used this to figure that out

mongoose.set('debug', function (coll, method, query, doc) {
    console.log(coll + " " + method + " " + JSON.stringify(query) + " " + JSON.stringify(doc));
});
like image 35
brandon Avatar answered Oct 06 '22 20:10

brandon


This is the proper way to use $elemMatch. I can't test your exact query because I don't have your schema. But there are a few ways:

let users = await User.find({
        pet_names: { 
            $elemMatch: { 
                $eq: 'Rex'
            }
        }
    });

But in your case, it looks like you're trying to query a property of an array element. You can also do:

db.users.find({ "boxes.a": "foo", "boxes.b": "bar"});
like image 1
David J Avatar answered Oct 06 '22 20:10

David J