.net - MongoDB .Net - 过滤数组子项中的项目
问题描述
我在 mongo 中有一个带有文档的集合。
{
_id: "1",
name: "test1",
active: true,
cars: [
{ _id: "2", name: "aaa", active: true },
{ _id: "3", name: "bbb", active: false },
{ _id: "4", name: "ccc", active: true },
},
{
_id: "2",
name: "test2",
active: false,
cars: [
{ _id: "10", name: "aaa", active: true }
}
我想只返回活动项目。在这个例子中:
{
_id: "1",
name: "test1",
active: true,
cars: [
{ _id: "2", name: "aaa", active: true },
{ _id: "4", name: "ccc", active: true },
}
我怎么做?
解决方案
您需要对$filter
非活动数组元素使用聚合管道
db.col.aggregate([
{$match : {"active" : true}},
{$addFields : {
cars : {
$filter : {
input : "$cars",
as : "c",
cond : "$$c.active"}
}
}}
])
结果
> db.col.aggregate([{$match : {"active" : true}},{$addFields : {cars : {$filter : {input : "$cars", as : "c", cond : "$$c.active"}}}}]).pretty()
{
"_id" : "1",
"name" : "test1",
"active" : true,
"cars" : [
{
"_id" : "2",
"name" : "aaa",
"active" : true
},
{
"_id" : "4",
"name" : "ccc",
"active" : true
}
]
}
推荐阅读
- winapi - 为什么 GetDIBits 的 MS 示例会创建一个新的 BITMAPINFOHEADER?
- apache-spark - Pyspark 将 PipelinedRDD 转换为 Spark DataFrame
- spring - 方面的声明正在打破上下文
- vue.js - 用户第一次访问页面时如何删除工具提示?
- jenkins - Jenkins 中的 HTML 报告
- heroku - 运行混合发布时,Heroku 审查应用程序上的 Elixir 构建失败并出现 (ArgumentError) 参数错误:erlang.binary_to_atom(nil, :utf8)
- python - 绘制图表但存在范围问题
- android - 为什么我在带有 Kotlin 的 Android Studio 中使用 async{} 后会得到 LiveData 的 null 值?
- html - 在 vb.net 中的 HTML5 类型周如何获取值?
- android - 将 MutableLiveData 传递给其他 ViewModel 是否有效?