根据 MongoDB 中的对象值获取相关信息 [英] get the relevant information against the object value in MongoDB
本文介绍了根据 MongoDB 中的对象值获取相关信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说明:A
, B
, C
对象有值.我只需要将那些值与 dic.data
对象名称匹配.如果它不匹配,则获取异常未找到错误".参见 Expected_output
.A
B
C
获取相关信息.
Explanation :
A
, B
, C
object have values. I have to match only those values with dic.data
objects name. if its not match the then get the exception "No error found". see the Expected_output
.
A
B
C
get the relvant information.
我正在使用 lookup
来获取 dic
数据.
I am using lookup
to get dic
data.
注意这应该是动态处理的.A
B
C
值可能不同,这会影响 Expected_output
Note this should be handle dynamically. A
B
C
values may differ, that impact on Expected_output
{
"_id": {
"A": "31",
"B": "40",
"C": "7"
},
"dic": [
{
"_id": "5487",
"data": {
"A": {
"31": {
"name": "NoFile"
},
"32": {
"name": " -- "
}
},
"B": {
"40": {
"label": "Label",
"description": "Error1"
},
"41": {
"label": " Data collection ",
"description": "error"
}
},
"C": {
"4": {
"description": "High problem"
},
"7": {
"description": " Normal"
}
}
}
}
]
}
"Expected_output": {
"A": {
"name" :"NoFile",
"code" : "31"
},
"B":{
"label" : "Label",
"description" : "Error1",
"code" : "40"
},
"C": {
"description" : "Normal",
"code" : "7"
}
}
推荐答案
$arrayElemAt
从dic
数组中获取第一个元素$objectToArray
将A
对象转换为数组$reduce
迭代转换数组上方元素的循环并检查条件是否_id.A
与数据A
匹配,然后返回特定字段,- 对
B
和C
做同样的处理
$arrayElemAt
to get first element fromdic
array$objectToArray
convertA
object to array$reduce
to iterate loop of element above converted array and check condition if_id.A
matches with dataA
then return specific field,- do the same process for
B
andC
db.collection.aggregate([
{
$addFields: {
dic: { $arrayElemAt: ["$dic", 0] }
}
},
{
$project: {
_id: 1,
dic: {
A: {
$reduce: {
input: { $objectToArray: "$dic.data.A" },
initialValue: "Not Found",
in: {
$cond: [
{ $eq: ["$$this.k", "$_id.A"] },
"$$this.v.name",
"$$value"
]
}
}
},
B: {
$reduce: {
input: { $objectToArray: "$dic.data.B" },
initialValue: "Not Found",
in: {
$cond: [
{ $eq: ["$$this.k", "$_id.B"] },
"$$this.v.description",
"$$value"
]
}
}
},
C: {
$reduce: {
input: { $objectToArray: "$dic.data.C" },
initialValue: "Not Found",
in: {
$cond: [
{ $eq: ["$$this.k", "$_id.C"] },
"$$this.v.description",
"$$value"
]
}
}
}
}
}
}
])
这篇关于根据 MongoDB 中的对象值获取相关信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文