mongodb - MongoDb中嵌套数组内的条件检查
问题描述
经过几个管道阶段后,我想出了以下示例结果,这是一个文档。如果videos.views.userId
包含10
,我需要指出videos.isWatched = true
其他false
。我们可以使用$unwind
,检查条件,然后group
它。
这是示例输出,原始文档包含很多字段,所以我只想用更少的代码来做,除非我需要unwind
有什么办法可以不用 unwind("videos")
吗?
[
{
"_id":"someId",
"videos":[
{
"_id":"1",
"name":"A",
"views":[
{
"userId":10,
"group":"X"
}
]
},
{
"_id":"2",
"name":"B",
"views":[
{
"userId":20,
"group":"Y"
}
]
}
],
"Assessment":[
{
"_id":"22",
"title": "Hello world"
}
]
}
]
预期结果
[
{
"_id":"someId",
"videos":[
{
_id:"1",
name:"A",
views:[
{
userId:10,
group:"X"
}
],
"isWatched":true
},
{
_id:"2",
name:"B",
views:[
{
userId:20,
group:"Y"
}
],
"isWatched":false
}
],
"Assessment":[
{
_id:"22",
title: "Hello world"
}
]
}
]
解决方案
您可以使用$map和$mergeObjects将新字段添加到现有数组。$anyElementTrue可用于确定是否有任何userId
等于10
:
db.collection.aggregate([
{
$addFields: {
videos: {
$map: {
input: "$videos",
in: {
$mergeObjects: [
"$$this",
{
isWatched: {
$anyElementTrue: {
$map: { input: "$$this.views", in: { $eq: [ "$$this.userId", 10 ] } }
}
}
}
]
}
}
}
}
}
])
推荐阅读
- wpf - 如何将组合框选择添加到数据网格
- android - Kotlin 中的 OOP 和函数式编程(设计)
- networkx - FileNotFoundError:[WinError 2] 在路径中找不到“neato”
- jquery - 我怎样才能访问这个对象?
- visual-studio-code - 显示属性的值而不仅仅是类型
- c# - 如何动画 listview 从视图模型中删除项目?
- python - 有没有办法从我的 cwd 创建两种类型的 xlsx 文档的两个数据帧
- angular - 从服务中删除数据不会从组件中删除
- qt - QDockwidget 的问题。被挤压到最小,只有按钮可见
- javascript - 如何将 2 个 Javascript 函数合二为一?