mongodb - Mongodb - 尝试进一步过滤到文档的子数组
问题描述
我有这样的数据
{
"_id":1,
"v_name":"Hair Patch in Delhi",
"v_url":"https://www.testurlvideo.com",
"v_comments":[
{
"user":"Kush Khurana",
"comment":"Awesome Video"
},
{
"user":"Nikhil",
"comment":"Keep up the good videos"
},
{
"user":"Kush Khurana",
"comment":"Very good and Awesome Video"
}
]
}
但我想要下面这样的数据
{
"_id":1,
"v_comments":[
{
"user":"Nikhil",
"comment":"Keep up the good videos"
}
]
}
我在 MongoDB 中需要什么查询?
解决方案
您只需要$filter
选择数组中的子文档并$project
只输出您想要的字段。
检查这个:
db.collection.aggregate([
{
"$match": {
"_id": 1
}
},
{
"$project": {
"v_comments": {
"$filter": {
"input": "$v_comments",
"as": "arr",
"cond": {
"$eq": [
"$$arr.user",
"Nikhil"
]
}
}
}
}
}
])
首先$match
是_id
(如果您只想在一个特定文档中查找,则可选)。
然后显示由那些对象过滤的$project
字段。这里的例子v_comments
user
Nikhil
推荐阅读
- swift - Swift 在尝试从存在的键中获取值时得到 Nil
- python - RelatedObjectDoesNotExist at / Accounts 没有客户
- java - 文件编写器无法在 do while 循环中正常工作
- javascript - 如何根据活动选项卡显示或不显示弹出窗口?
- git - Git::Repository 和草莓 Perl
- neural-network - 如何修改预训练的 Resnet 模型
- linux - 在文件夹名称中的字符之间传输一些短语
- python - 在 MATLAB 中读取 dict 的 python pickle 会导致错误
- sql-server - 如何克服 Microsoft SQL Server 中 IN 运算符的资源限制
- google-chrome-extension - Chrome 扩展 ID,对所有用户安装的浏览器都一样吗?