mongodb - 蒙古数据库。获取其数组字段仅包含查询中的单词的文档
问题描述
是否可以在 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"
]
]
}
}
]
}
}
}
])
推荐阅读
- c - 在函数中使用 malloc 和 realloc 进行 C 练习
- html - 桌面 4 列,小型设备 2 列
- react-admin - 在 react-admin 中创建可折叠的左侧菜单
- .net - WPF中图像上的可移动文本注释(定制)
- python - python中的互斥命令单击
- qt - Disable view move when dragging mouse in QGraphicsView
- html - Align contents of two table columns together
- typescript - how to write unit test case for the saga with multiple yield calls with are based on the response of an action
- java - Is it possible to start a native executable from android native layer?
- powershell - 如何在 Powershell 中使用逗号列表连接和分组 2 个表?