我目前有一個結構化的資料庫,如
return new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
name: {type: String, unique: false, required: true},
criteria: [
{
_id: {
type: mongoose.Schema.Types.ObjectId,
auto: true
},
category: {type: String, required: false},
links: {type: [String], required: false, default: []},
dateOfEntry: {
type: Date,
default: new Date(),
required: true
},
lastUpdated: {
type: Date,
default: new Date(),
required: true
}
}
],
isActive: {type: Boolean, required: false, default: true}});
樣本資料
[
{
"name": "item1",
"criteria": [
{
"category": "category_A",
"links": [
"link_issue1",
"link_issue2",
"link_issue3"
]
},
{
"category": "category_B",
"links": [
"link_issue1",
"link_issue2"
]
},
]
},
{
"name": "item2",
"criteria": [
{
"category": "category_C",
"links": []
},
]
}
]
所以現在,我想將鏈接的資料型別從陣列更改為字串并更新現有資料
我的預期像
[
{
"name": "item1",
"criteria": [
{
"category": "category_A",
"links": "link_issue1,link_issue2,link_issue3"
},
{
"category": "category_B",
"links": "link_issue1,link_issue2"
},
]
},
{
"name": "item2",
"criteria": [
{
"category": "category_C",
"links": ""
},
]
}
]
我的資料庫有大約 500-1000 條記錄需要更新。那么我們可以通過 MongoDB shell 更新它們嗎?非常感謝你的幫助。
uj5u.com熱心網友回復:
利用 $concat
db.collection.update({},
[
{
$set: {
criteria: {
$map: {
input: "$criteria",
as: "c",
in: {
category: "$$c.category",
links: {
"$reduce": {
"input": "$$c.links",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this",
{
$cond: {
if: {
"$eq": [
{ $subtract: [ { $size: "$$c.links" }, 1 ] },
{ $indexOfArray: [ "$$c.links", "$$this" ] }
]
},
then: "",
else: ","
}
}
]
}
}
}
}
}
}
}
}
],
{
"multi": true
})
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/387320.html
標籤:MongoDB 猫鼬 mongodb-查询
下一篇:聚合時貓鼬更新檔案
