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"});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With