mongodb - 查找具有仅包含特定值而没有其他内容的数组字段的文档
问题描述
考虑这个集合:
{
{ name: 'first', toys: ['doll', 'car', 'doll'],
{ name: 'second', toys: ['doll', 'car'],
{ name: 'third', toys: ['doll', 'car', 'bricks'],
{ name: 'fourth', toys: ['doll', 'bricks'],
{ name: 'fifth', toys: []
}
我想查询其toys
字段是仅包含doll
and的数组的文档car
。在这种情况下,两者first
和second
应该匹配。first
匹配是因为doll
andcar
可以在数组中重复,third
不匹配是因为数组中不能存在其他值,fourth
andfifth
不匹配是因为它们不包含doll
and car
。
使用$all
and$in
对我不起作用,因为它们匹配third
. 我怎样才能做到这一点?谢谢!
解决方案
更好的方法是使用聚合运算符$setEquals
比较两个或多个数组,如果它们具有相同的不同元素,则返回 true,否则返回 false:
db.collection.find({
'$expr': {
'$setEquals': ['$toys', ['doll', 'car']]
}
})
另一种选择是$setDifference
采用两个数组并执行第二个数组相对于第一个数组的相对补码,并且此操作不需要元素按顺序排列。
在您的情况下,使用结果$setDifference
来检查其是否为空并将其设置为查询的基础。
例如操作
{ $setDifference: [ ['doll', 'car', 'doll'], ['doll', 'car'] ] } => []
还有这个
{ $setDifference: [ ['car', 'doll', 'doll'], ['doll', 'car'] ] } => []
也
{ $setDifference: [ ['car', 'doll'], ['doll', 'car'] ] } => []
或者
{ $setDifference: [ ['doll', 'car'], ['doll', 'car'] ] } => []
但
{ $setDifference: [ ['doll', 'car', 'bricks'], ['doll', 'car'] ] } => ['bricks']
使用上面的逻辑,作为助手,您可以获取数组结果的长度$size
并检查它是否为 0 用于您的查询表达式$expr
最终查询:
db.collection.find({
'$expr': {
'$eq': [
{ '$size': {
'$setDifference': [
'$toys',
['doll', 'car']
]
} },
0
]
}
})
推荐阅读
- c++ - 为没有 qmake/VS 的 Qt Windows 应用程序设置 .exe 图标
- c - 当给定字母的字典顺序时,合并排序的时间复杂度是多少?
- google-data-studio - 有没有办法将当前时间戳添加到 Google Data Studio 报告中?
- android - 在 textView 中打印一个 json 文件
- javascript - 在 Jquery 中的单击功能在计算机上使用时不起作用
- png - 将ai文件转换为png后字体失真
- elm - 如何退出 elm repl?
- android - 如何在电话信息中读取 Android IP 地址状态?
- hyperledger-fabric - Hyperledger Fabric:缺少 etcdraft 配置
- javascript - Javascript频率计数器算法