mongodb - Mongo addFields 从嵌套数组中获取值
问题描述
我想fieldValue
根据给定的fieldName
.
例如:按 fieldName = 'Author' 对集合进行排序
我的问题:我无法从集合中获取值,就像我想为 authorValue 添加一个字段一样。
{ ....作者:'约翰'},{作者:'Hengry'}
我试过的:
.addFields({
author: {
$filter: {
input: "$sections.fieldData",
cond: {
$eq: ["$$this.fieldName", true],
},
},
},
结构
[
{
"sections": [
{
name: "section1",
fields: [
{
fieldName: "Author",
fieldValue: "John"
},
{
fieldName: "Movie",
fieldValue: "Avenger"
}
]
}
]
},
{
"sections": [
{
name: "section1",
fields: [
{
fieldName: "Author",
fieldValue: "Hengry"
},
{
fieldName: "Movie",
fieldValue: "Test"
}
]
}
]
}
]
解决方案
You can use $reduce
to iterate your array and extract out the fieldValue
for comparison.
db.collection.aggregate([
{
"$addFields": {
"sortField": {
"$reduce": {
"input": "$sections",
"initialValue": null,
"in": {
"$reduce": {
"input": "$$this.fields",
"initialValue": null,
"in": {
"$cond": {
"if": {
$eq: [
"$$this.fieldName",
"Author"
]
},
"then": "$$this.fieldValue",
"else": "$$value"
}
}
}
}
}
}
}
},
{
$sort: {
sortField: 1
}
},
{
"$project": {
sortField: false
}
}
])
Here is the Mongo playground for your reference.
推荐阅读
- vue.js - 为什么 vue-loader 不能与故事书一起使用?
- javascript - 如何获取模板html中的元素?
- java - Spark Graphx java.lang.OutOfMemoryError
- html - 动态图像和媒体查询 - 有没有办法同时使用两者?
- javascript - 具有网格重新排序功能的可拖动网格
- ruby-on-rails - Capistrano rails deploy 升级到 rails 5.1.5 失败,仍将当前设置为失败部署
- sql-server - 如何在以前的时间点恢复 SQL Server 数据库
- react-native - 如何从 React Native 中的 SQL 提取中获取一个字段?
- javascript - 将多个对象归为一个
- vb.net - VB替换附加csv中的字符