gpt4 book ai didi

MongoDB - 将数组拆分为多个文档并用数组对象替换现有文档

转载 作者:行者123 更新时间:2023-12-05 02:08:30 30 4
gpt4 key购买 nike

我有一个像这样的大 json 文档:

{
"_id": {
"$oid": "5e7a50e7f1d41b3ea05aa46e"
},
"response": {
"count": 2,
"items": [
{
"id": 1,
"first_name": "Unknown",
"last_name": "Unknown",
"is_closed": false,
"can_access_closed": true,
"photo": "1.jpg",
"track_code": "d9e2ca2eG4GbHAQSwz8Ne4WBiVx"
},
{
"id": 2,
"first_name": "Lorem",
"last_name": "Ipsum",
"is_closed": false,
"can_access_closed": true,
"photo": "2.jpg",
"track_code": "23f1219a7j1xyWba69jz7p"
}
]
}
}

如何按集合中的单个对象(例如按项目中的 ID)拆分“项目”?结果我想要这样的东西:

对象 #1

{
"_id": {
"$oid": "5e7a50e7f1d41b3ea05aa46e"
},
"id": 1,
"first_name": "Unknown",
"last_name": "Unknown",
"is_closed": false,
"can_access_closed": true,
"photo": "1.jpg",
"track_code": "d9e2ca2eG4GbHAQSwz8Ne4WBiVx"
}

对象 #2

{
"_id": {
"$oid": "ae2a40e7ffd41b3ea05aa46e"
},
"id": 2,
"first_name": "Lorem",
"last_name": "Ipsum",
"is_closed": false,
"can_access_closed": true,
"photo": "2.jpg",
"track_code": "23f1219a7j1xyWba69jz7p"
}

我不明白如何在文档中查找它。

最佳答案

您可以尝试下面的查询,因为我们正在分解 items 数组,因此您的结果中的文档数量可能比集合中的实际数量更多:

db.collection.aggregate([
/** Adds '_id' field to each object inside items array, this can be done after 'unwind',
* if it's done after 'unwind' no.of docs to be iterated in 'unwind' is more, So better be done as first stage*/
{
$addFields: {
"response.items._id": "$_id"
}
},
/** Unwind items array, will exclude docs where items is not an array/doesn't exists */
{
$unwind: "$response.items"
},
/** Replace 'response.items' object as new root(document) */
{
$replaceRoot: {
newRoot: "$response.items"
}
}
])

测试: MongoDB-Playground

引用: aggregation-pipeline

关于MongoDB - 将数组拆分为多个文档并用数组对象替换现有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60838526/

30 4 0
文章推荐: javascript - 警告 : Expected server HTML to contain a matching in
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com