mongodb使用$ in查询多个对 [英] mongodb query multiple pairs using $in
本文介绍了mongodb使用$ in查询多个对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含数据的集合names
(省略了_id):
I have a collection names
with data (_id is omitted):
{first:"John", last:"Smith"},
{first:"Alice", last:"Johnson"},
{first:"Bob", last:"Williams"},
...
和{first, last}
是唯一索引.
我想在names
中找到很多名字,例如:
I want to find a lot of names in names
like:
db.names.find({$or: [{first:"Alice", last:"Brown"}, {first:"Bob", last:"White"}, ...]}
我可以使用$in
代替$or
来简化此查询吗?
Can I use $in
instead of $or
to simplify this query?
===
我在MySQL中知道以下查询:
I know in MySQL this following query:
SELECT * FROM names WHERE (first = 'Alice' AND last = 'Brown') OR (first = 'Bob' AND last = 'White') OR ...
可以简化为:
SELECT * FROM names WHERE (first, last) IN (('Alice', 'Brown'), ('Bob','White') OR ...)
但是我无法在MongoDB中找到等效的查询语法.
But I am unable to find the equivalent query syntax in MongoDB.
推荐答案
对此mysql查询
SELECT * FROM names
WHERE (first = 'Alice' AND last = 'Brown')
OR (first = 'Bob' AND last = 'White')
OR ...
可以在mongodb中用作
can be use in mongodb as
db.names.find({
$or: [
{ first: "Alice", last: "Brown" },
{ first: "Bob", last: "White" },
...
]})
对于下面的mysql查询
For below mysql query
SELECT * FROM names
WHERE (first, last) IN (('Alice', 'Brown'), ('Bob','White') OR ...)
您不能创建mongodb $ in 查询>
You can not create mongodb $in query
db.names.find({
$or: [
{ first: { $in: ["John", "Alice", "Bob"] } },
{ last: { $in: ["Smith", "Johnson", "Williams" ] } },
]})
因为它也通过了此结果
("John", "Johnson"),("John", "Williams"),("John", "Smith"),("John", "Williams")..
最好的方法是
db.names.find({
$or: [
{ first: "Alice", last: "Brown" },
{ first: "Bob", last: "White" },
...
]})
可能是更好的解决方案.如果有的话,我将更新我的答案.谢谢
May be better solution present out there. I will update my answer if find any. Thanks
这篇关于mongodb使用$ in查询多个对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文