如何解决$ eq运算符可以和数组点符号一起使用吗?
我正在尝试在$query_result = DB::select("SELECT `picture`
FROM `scraper_profile_data` pd
INNER JOIN `scraper_collection_entries` ce ON ce.`item_id` = pd.`profile_id`
WHERE ce.`collection_id` = " . $this->id .
"ORDER BY ce.`created_at` DESC
LIMIT 10;");
$result = collect($query_result)->pluck('picture')->toArray();
return $result;
的{{1}}流水线阶段中使用$expr
编写聚合查询。我发现了一些与数组点表示法有关的问题。
想象一下一个集合$lookup
,其数组字段名为$match
。
以下查询可以很好地返回正确的结果:
relations
但是下面的一个什么都不返回:
nodes
在我看来,它们实际上是相同的,而且我不明白为什么结果会有所不同。
我尝试使用db.relations.find({"nodes.0": { "type" : "User","id" : UUID("dc20f7c7-bd45-4fc1-9eb4-3604428fa551") }})
运算符,但可以运行,但是不幸的是,它触发了COLLSCAN执行计划,这是不理想的,因为我在db.relations.find({$expr: {$and: [ {$eq: ["$nodes.0",{ "type" : "User","id" : UUID("dc20f7c7-bd45-4fc1-9eb4-3604428fa551") }]}]}})
上有索引。
我在文档中没有发现关于$arrayElemAt
运算符的任何特别之处,他们甚至明确提到这两种表达形式是等效的。
解决方法
$eq
运算符可以使用数组点表示法吗?
不。与数组字段一起使用时,$nodes.0
在$eq aggregation operator
中不是正确的表达式。
$eq aggregation operator
具有以下语法:
{ $eq: [ <expression1>,<expression2> ] }
您必须使用$reduce
和$arrayElemAt
来访问$ eq运算符中的字段:
查询1
db.relations.find({
$expr: {
$eq: [
{
$reduce: {
input: [
{
$arrayElemAt: [
"$nodes",0
]
}
],initialValue: false,in: {
"$and": [
{
$eq: [
"$$this.type","User"
]
},{
$eq: [
"$$this.id",UUID("dc20f7c7-bd45-4fc1-9eb4-3604428fa551")
]
}
]
}
}
},true
]
}
})
或者,使用$ eq运算符{ <field>: { $eq: <value> } }
Query2
db.relations.find({
"$and": [
{
"nodes.0.type": {
$eq: "User"
}
},{
"nodes.0.id": {
$eq: UUID("dc20f7c7-bd45-4fc1-9eb4-3604428fa551")
}
}
]
})
如果要执行IXSCAN,则可以使用 Query2 。您必须创建以下索引:
db.relations.ensureIndex({"nodes.0.id":1})
db.relations.ensureIndex({"nodes.0.type":1})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。