简体   繁体   English

如何在 mongoose 中使用 elemMatch 进行查询?

[英]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:我正在尝试根据以下 mongodb 查询在我的 mongodb 集合中查询用户:

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

This works if I query directly with mongodb.如果我直接使用 mongodb 查询,这会起作用。 It returns any user that has a box with a="foo" and b="bar".它返回任何拥有带有 a="foo" 和 b="bar" 的框的用户。

How can I query this in mongoosejs?我如何在 mongoosejs 中查询这个? I've tried using User.find().elemMatch but it doesn't work.我试过使用User.find().elemMatch但它不起作用。 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.不过,原始的 mongodb 查询确实对我有用,我只需要能够在 mongoosejs 中复制它。 Any ideas?有任何想法吗?

Documentation for elemMatch in mongoose is here .猫鼬中的 elemMatch 文档在这里
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 Tim 的回答是正确的,但是如果有人对 mongoose 为 mongo native API 上的查询生成的内容感到困惑,我用它来解决这个问题

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.这是使用 $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"});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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