mongodb - MongoDB 区分然后过滤
问题描述
假设我有一个藏书:
{"name": "Mongodb", "authors": [{"name": "John"}, {"name": "Peter"}, {"name": "Joe"}]}
{"name": "MySQL", "authors": [{"name": "John"}, {"name": "Alice"}, {"name": "Kate"}]}
{"name": "SQL Server", "authors": [{"name": "John"}, {"name": "Steve"}]}
我想找到与John
.
当我使用查询时:db.book.distinct('authors.name', {'authors.name': 'John'})
它将返回以下结果:[John, Peter, Joe, Alice, Kate, Steve]
但是,我不想John
在列表中。
我怎样才能做到这一点?
解决方案
你去:
db.book.aggregate({
$match: {
"authors.name": "John" // only look at documents that contain "John" in the list of authors (this part could use an index on "authors.name")
}
}, {
$unwind: "$authors" // flatten the authors array into separate documents
}, {
$group: {
_id: null, // throw all documents in the same bucket
authors: { $addToSet: "$authors.name" } // add all authors' names into an array called "authors" eliminating duplicate entries
}
}, {
$project: {
"co-authors": {
$filter: { // remove "John" from the list of entries
"input": "$authors",
"as": "this",
"cond": { $ne: [ "$$this", "John" ] }
}
}
}
})
但是,我认为您当前的“解决方案”更加优雅。它所缺少的只是一点点客户端过滤(从返回的条目列表中删除“John”条目)。
推荐阅读
- javascript - 我们如何禁用输入类型 =“日期”中的 dd-mm-yyyy 字段,以便只接受选定的日期
- karate - 使用 karate.forEach 和 karate.set 从 json 数组中提取值的索引
- javascript - Firebase 网络将聊天存储为实时数据库中的数组
- java - 为什么eclipse不在方法参数中使用菱形运算符
- python - 将具有嵌套列表的列转换为以第一个元素作为列名的列
- java - Netflix Eureka 错误:com.netflix.discovery.shared.transport.TransportException:无法在任何已知服务器上执行请求
- javascript - 如何获得“未过滤”的数组项?
- visual-studio-code - 如何在 vscode 语法中的范围匹配后隔离尾随文本的范围
- exception - 在 Kotlin 中指示方法不会引发异常的注解
- regex - 使用正则表达式显示重复字符串