是否可以在mongodb中找到字段中所有单词都包含在查询中的文档,反之亦然?
伪查询:
{title:
{$in: ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]}
}
文档:
{'title': ["brown", "fox"} #true
{'title': ["lazy", "dog"]} #true
{'title': ["lazy", "dog", "sleep"]} #false 'sleep' not in query
{'title': ["brown", "dog"]} #true
{'title': ["jumps", "quick"]} #true
{'title': ["smile", "fox"]} #false 'smile' not in query
MongoDB聚合提供了比标准.find
方法更多的操作。
采用两个或多个数组并返回一个包含每个输入数组中显示的元素的数组。 https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/#exp._S_setIntersection
一旦我们得到交集,我们比较数组大小(我假设你的数组不能有重复的值(
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [
{
$size: "$title"
},
{
$size: {
$setIntersection: [
"$title",
[
"the",
"quick",
"brown",
"fox",
"jumps",
"over",
"the",
"lazy",
"dog"
]
]
}
}
]
}
}
}
])
蒙戈游乐场