mongodb - 根据条件查找和计算 mongo 数组中的重合
问题描述
想象一下,我有一组类似于以下内容的文档:
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article one",
topic:["config","develop","show"],
keys[
{subject:"one",object"abc"},
{subject:"one",object"def"},
{subject:"two",object"ghi"},
{subject:"four",object"jkl"},
{subject:"four",object"mnl"},
{subject:"four",object"mnl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article two",
topic:["config","installing"],
keys[
{subject:"one",object"abc"},
{subject:"one",object"def"},
{subject:"two",object"ghi"},
{subject:"two",object"jkl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article three",
topic:["config","installing"],
keys[
{subject:"five",object"abc"},
{subject:"five",object"def"},
{subject:"two",object"ghi"},
{subject:"two",object"jkl"},
]
}
我想根据条件计算数组中的每个主题,按主题过滤,例如,假设我按主题搜索:“config”和主题:[“one”,“four”] 结果需要是
{article :"article one", sum:5},{article :"article two", sum:2}
提前谢谢
解决方案
You can use below aggregation.
db.colname.aggregate([
{"$match":{"topic":"config","subject":{"$in":["one","four"]}}},
{"$project":{
"article":1,
"sum":{
"$size":{
"$filter":{
"input":"$keys",
"cond":{"$in":["$$this.subject",["one","four"]]}
}
}
}
}}
])
推荐阅读
- java - 泽西岛 - java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
- rust - 使活塞窗口透明
- ruby - GetStream:以下提要不返回提要的项目
- templates - 新的 ASP.Net Core Web 应用程序屏幕 Visual Studio 2017 中没有 ASP.Net Core 模板
- python - Keras 中时间一维卷积的输入形状错误
- twitter-bootstrap - 如何通过单击视口中的任意位置来关闭 Bootstrap/Lightbox 模式?
- java - 如何在另一个类中调用“写入文件”方法?
- php - 如何防止子查询返回超过 1 行
- php - 警告:mysqli_connect(): (HY000/1045): Access denied for user 'usr'@'localhost' (使用密码: YES)
- python-3.x - 如何从spacy vocab中获取所有单词?