gpt4 book ai didi

mongodb - mongo 将单个对象转换为一个元素数组

转载 作者:行者123 更新时间:2023-12-04 03:30:48 26 4
gpt4 key购买 nike

我有以下问题。在这个示例数据集中:

https://mongoplayground.net/p/itNnrDzZ4JQ

[
{
"name": "test",
"questions": [
{
"headline": "headline 1",
"answer": {
"@id": "001",
"m_IMG": {
"type": "06",
"img": {
"@id": "1111",
"shape": [
{
"@src": "/1_1.jpg",
"@type": "Z05"
},
{
"@src": "/1_2.jpg",
"@type": "Z08"
}
]
}
},
"text": "text1"
}
},
{
"headline": "Headline 2",
"answer": [
{
"@id": "001",
"m_IMG": {
"@type": "24",
"img": {
"@id": "1111",
"shape": {
"@src": "/2_1.jpg",
"@type": "Z05"
}
},
"text": "Test2"
}
},
{
"@id": "002",
"m_IMG": {
"@typeName": "",
"@type": "25",
"img": {
"@id": "2222",
"shape": [
{
"@src": "/2_1.jpg",
"@type": "Z05"
},
{
"@src": "2_2.jpg",
"@type": "Z08"
}
]
}
},
"text": "Test3"
}
]
}
]
}
]

您会发现,如果一个问题只有一个答案,则它会被表示为一个对象。如果存在多个,则它是一个数组。 shape 节点也是如此。我想知道将这些节点转换为始终数组的最佳方法是什么(因此,如果存在一个答案,它将是一个元素的数组)。

最佳答案

  • $map 迭代 questions 数组的循环
  • 检查条件,如果答案不是数组,然后将其放入数组括号中,并作为$map输入,以迭代answer数组的循环
  • 检查条件是否不是shape数组十将其包裹到数组括号中
  • $mergeObjects 带有子文档 img, m_IMG 对象
  • $mergeObjects 包含当前文档和更新的 answer 数组
db.collection.aggregate([
{
$set: {
questions: {
$map: {
input: "$questions",
as: "q",
in: {
$mergeObjects: [
"$$q",
{
answer: {
$map: {
input: {
$cond: [
{ $eq: [{ $isArray: "$$q.answer" }, true] },
"$$q.answer",
["$$q.answer"]
]
},
as: "a",
in: {
$mergeObjects: [
"$$a",
{
m_IMG: {
$mergeObjects: [
"$$a.m_IMG",
{
img: {
$mergeObjects: [
"$$a.m_IMG.img",
{
shape: {
$cond: [
{ $eq: [{ $isArray: "$$a.m_IMG.img.shape" }, true] },
"$$a.m_IMG.img.shape",
["$$a.m_IMG.img.shape"]
]
}
}
]
}
}
]
}
}
]
}
}
}
}
]
}
}
}
}
}
])

Playground

关于mongodb - mongo 将单个对象转换为一个元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66853444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com