简体   繁体   中英

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM