sql - mongodb 使用 $in 查询多对
问题描述
我有一个names
包含数据的集合(省略了_id):
{first:"John", last:"Smith"},
{first:"Alice", last:"Johnson"},
{first:"Bob", last:"Williams"},
...
并且{first, last}
是唯一索引。
我想找到很多names
类似的名字:
db.names.find({$or: [{first:"Alice", last:"Brown"}, {first:"Bob", last:"White"}, ...]}
我可以使用$in
而不是$or
简化此查询吗?
===
我在 MySQL 中知道以下查询:
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 中找到等效的查询语法。
解决方案
以下查询可以为我们提供预期的输出:
db.names.find({
$expr:{
$in:[
{
"first":"$first",
"last":"$last"
},
[
{
"first" : "Alice",
"last" : "Johnson"
},
{
"first" : "Bob",
"last" : "Williams"
}
]
]
}
}).pretty()
数据集:
{
"_id" : ObjectId("5d81c3b7a832f81a9e02337b"),
"first" : "John",
"last" : "Smith"
}
{
"_id" : ObjectId("5d81c3b7a832f81a9e02337c"),
"first" : "Alice",
"last" : "Johnson"
}
{
"_id" : ObjectId("5d81c3b7a832f81a9e02337d"),
"first" : "Bob",
"last" : "Williams"
}
输出:
{
"_id" : ObjectId("5d81c3b7a832f81a9e02337c"),
"first" : "Alice",
"last" : "Johnson"
}
{
"_id" : ObjectId("5d81c3b7a832f81a9e02337d"),
"first" : "Bob",
"last" : "Williams"
}
查询分析:此查询不会使用您创建的唯一索引,我建议使用 $or 查询。
以下是获奖计划:
$或查询:
{
"stage" : "COLLSCAN",
"filter" : {
"$expr" : {
"$in" : [
{
"first" : "$first",
"last" : "$last"
},
{
"$const" : [
{
"first" : "Alice",
"last" : "Johnson"
},
{
"first" : "Bob",
"last" : "Williams"
}
]
}
]
}
},
"direction" : "forward"
}
$in 查询:
{
"stage" : "SUBPLAN",
"inputStage" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "OR",
"inputStages" : [
{
"stage" : "IXSCAN",
"keyPattern" : {
"first" : 1,
"last" : 1
},
"indexName" : "first_1_last_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"first" : [ ],
"last" : [ ]
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"first" : [
"[\"Alice\", \"Alice\"]"
],
"last" : [
"[\"Brown\", \"Brown\"]"
]
}
},
{
"stage" : "IXSCAN",
"keyPattern" : {
"first" : 1,
"last" : 1
},
"indexName" : "first_1_last_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"first" : [ ],
"last" : [ ]
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"first" : [
"[\"Bob\", \"Bob\"]"
],
"last" : [
"[\"White\", \"White\"]"
]
}
}
]
}
}
}
您可以看到索引在 $or 查询中被正确使用,而在 $in 查询中没有使用。
推荐阅读
- r - 如何在 dplyr summarise() 中排除 NA 值?
- python-3.x - 将 dict 转换为 numPy 数组
- python - 使用 Scrapy 递归地从 href 中提取文本
- r - pdfsearch "pdf 中无法识别的文本"
- python - 插入网页的音频文件没有采取行动,请在此处帮助我
- javascript - 确定字符串中的组
- mysql - 启用 innodb_dedicated_server 对性能有好处吗?
- java - 如何在 mac 上授予使用 jpackage 全盘访问权限打包的 java 应用程序?
- reactjs - 反应修改道具以在子组件中按排序顺序显示行
- django - 如何在 Django 中使用带有块内容的引导选项卡