gpt4 book ai didi

mongodb - 根据两个值查找元素

转载 作者:可可西里 更新时间:2023-11-01 09:39:14 24 4
gpt4 key购买 nike

我正在尝试对我的测试集合做一个简单的查找

这是一个条目示例:

{
"_id": "movie:1",
"title": "Vertigo",
"year": 1958,
"genre": "drama",
"summary": "Scottie Ferguson, ancien inspecteur de police, est sujet au vertige depuis qu'il a vu mourir son collègue. Elster, son ami, le charge de surveiller sa femme, Madeleine, ayant des tendances suicidaires. Amoureux de la jeune femme Scottie ne remarque pas le piège qui se trame autour de lui et dont il va être la victime... ",
"country": "DE",
"director": {
"_id": "artist:3",
"last_name": "Hitchcock",
"first_name": "Alfred",
"birth_date": "1899"
},
"actors": [
{
"_id": "artist:15",
"first_name": "James",
"last_name": "Stewart",
"birth_date": "1908",
"role": "John Ferguson"
},
{
"_id": "artist:16",
"first_name": "Kim",
"last_name": "Novak",
"birth_date": "1925",
"role": "Madeleine Elster"
},
{
"_id": "artist:282",
"first_name": "Arthur",
"last_name": "Pierre",
"birth_date": null,
"role": null
}
]
}

我想找导演兼 Actor 的电影。是否可以用一个简单的 $elemMatch 来做到这一点:

find({actors: {$elemMatch: {"_id": "this.director._id"} })

谢谢!

最佳答案

来自previously linked dupe (possible) ,一个使用 $where 的解决方案 将遵循:

db.collection.find({
"$where": function() {
self = this;
return this.actors.filter(function(actor) {
return self.director._id === actor._id;
}).length > 0
}
})

以及使用聚合框架的其他建议方法 $redact 管道:

db.collection.aggregate([
{
"$redact": {
"$cond": [
{
"$setIsSubset": [
["$director._id"],
{
"$map": {
"input": "$actors",
"as": "el",
"in": "$$el._id"
}
}
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
])

在上面, $redact 的条件逻辑 是通过使用集合运算符 $setIsSubset 完成的 $map

$map 运算符将返回一个仅包含来自 actors 的 Actor ID 的数组。对数组中的每个元素应用表达式后的数组。例如,表达式

{
"$map": {
"input": "$actors",
"as": "el",
"in": "$$el._id"
}
}

如果应用于 Actor 数组

[ 
{
"_id" : "artist:3",
"first_name" : "James",
"last_name" : "Stewart",
"birth_date" : "1908",
"role" : "John Ferguson"
},
{
"_id" : "artist:16",
"first_name" : "Kim",
"last_name" : "Novak",
"birth_date" : "1925",
"role" : "Madeleine Elster"
},
{
"_id" : "artist:282",
"first_name" : "Arthur",
"last_name" : "Pierre",
"birth_date" : null,
"role" : null
}
]

会回来

[ "artist:3", "artist:16", "artist:282" ]

此结果与单个元素数组进行比较 ["$directors._id"]使用 $setIsSubset 运算符,它接受两个数组,并在第一个数组是第二个数组的子集(包括第一个数组等于第二个数组时)时返回 true,否则返回 false。

例如,

{ 
"$setIsSubset": [
[ "artist:12" ],
[ "artist:3", "artist:16", "artist:282" ]
]
} // false

{
$setIsSubset: [
[ "artist:282" ],
[ "artist:3", "artist:16", "artist:282" ]
]
} // true

运算符的 bool 结果然后用作 $redact 的基础 管道。

对性能的解释仍然成立: $where 在必要时是一个很好的 hack,但应尽可能避免。

关于mongodb - 根据两个值查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com