[MongoDB]:更改所有數組字段中的值類型 ([MongoDB]: Changing the type of values in all array fields)


問題描述

[MongoDB]:更改所有數組字段中的值類型 ([MongoDB]: Changing the type of values in all array fields)

我有 authorsbooks 測試集合,它們之間具有多對多關係。

> db.books.find()
[
  {
    _id: ObjectId("60a676f24312c6d8ea7bd6ec"),
    title: '300 years of peanut juggling: A longitudinal analysis.',
    inPrint: true,
    authors: [ '60a673c44312c6d8ea7bd6e9', '60a673c44312c6d8ea7bd6ea' ]
  },
  {
    _id: ObjectId("60a676f24312c6d8ea7bd6ed"),
    title: "Mystery Overflow: murder and chaos on the Web's biggest developer Q & A platform.",
    inPrint: true,
    authors: [ '60a673c44312c6d8ea7bd6eb' ],
    edition: 2
  }
]
> db.authors.find()
[
  {
    _id: ObjectId("60a673c44312c6d8ea7bd6e9"),
    name: 'Jason Filippou',
    age: 33,
    nationalities: [ 'GRC, CND' ],
    books: [ '60a676f24312c6d8ea7bd6ec' ]
  },
  {
    _id: ObjectId("60a673c44312c6d8ea7bd6ea"),
    name: 'Mary Chou',
    age: 39,
    nationalities: [ 'USA' ],
    books: [ '60a676f24312c6d8ea7bd6ec' ]
  },
  {
    _id: ObjectId("60a673c44312c6d8ea7bd6eb"),
    name: 'Max Schwarz',
    age: 42,
    job: 'pilot',
    books: [ '60a676f24312c6d8ea7bd6ed' ]
  }
]

我在外部實現該關係,如 authorsbooks 字段所示。但是,我犯了一個錯誤,即讓引用數組是原始字符串,而不是 ObjectId 類型。這意味著我的連接(例如,$lookup()) 失敗。

我嘗試批量更新所有字符串以使它們成為 ObjectIds 使用命令:

db.books.find({}).forEach(book => book.authors.forEach(id => ObjectId(id)))

雖然命令有效,但原始數據沒有改變:

> db.books.find({}).forEach(book => book.authors.forEach(id => ObjectId(id)))

> db.books.find()
[
{
_id: ObjectId("60a676f24312c6d8ea7bd6ec"),
title: '300 years of peanut juggling: A longitudinal analysis.',
inPrint: true,
authors: [ '60a673c44312c6d8ea7bd6e9', '60a673c44312c6d8ea7bd6ea' ]
},
{
_id: ObjectId("60a676f24312c6d8ea7bd6ed"),
title: "Mystery Overflow: murder and chaos on the Web's biggest developer Q & A platform.",
inPrint: true,
authors: [ '60a673c44312c6d8ea7bd6eb' ],
edition: 2
}
]
> db.authors.find()
[
{
_id: ObjectId("60a673c44312c6d8ea7bd6e9"),
name: 'Jason Filippou',
age: 33,
nationalities: [ 'GRC, CND' ],
books: [ '60a676f24312c6d8ea7bd6ec' ]
},
{
_id: ObjectId("60a673c44312c6d8ea7bd6ea"),
name: 'Mary Chou',
age: 39,
nationalities: [ 'USA' ],
books: [ '60a676f24312c6d8ea7bd6ec' ]
},
{
_id: ObjectId("60a673c44312c6d8ea7bd6eb"),
name: 'Max Schwarz',
age: 42,
job: 'pilot',
books: [ '60a676f24312c6d8ea7bd6ed' ]
}
]
</code></pre>


參考解法

方法 1:

If you decide to update all books string to ObjectId, u can use update‑documents‑with‑aggregation‑pipeline

db.authors.updateMany({},[
  {
    "$addFields": {
      "books": {
        "$map": {
          "input": "$books",
          "in": {
            "$toObjectId": "$$this"
          }
        }
      }
    }
  }
])

(by Jasonvarman)

參考文件

  1. [MongoDB]: Changing the type of values in all array fields (CC BY‑SA 2.5/3.0/4.0)

#mongo-shell #mongodb-update #mongoDB #objectid






相關問題

Windows 是否有任何 mongo shell 擴展? (Is there any mongo shell extensions for windows?)

獲取查詢中所有文檔的大小 (Get the size of all the documents in a query)

如何從 java 程序運行 mongo 查詢? (How to run a mongo query from java program?)

MongoDB 更新 ObjectId 字段 (MongoDB update ObjectId field)

MongoDB - 將簡單字段更改為對象 (MongoDB - change simple field into an object)

mongoDB aggregate() 在電子郵件對象集合中查找電子郵件時間 (mongoDB aggregate() finding email times in a collection of email objects)

指定在 mongodb .js 腳本中使用哪個數據庫 (Specify which database to use in mongodb .js script)

命令失敗:MongoError:CMD_NOT_ALLOWED:配置文件 (command failed: MongoError: CMD_NOT_ALLOWED: profile)

有沒有辦法在 MongoDB 的一個語句中添加遞增的 id? (Is there a way to add an incrementing id in one statement in MongoDB?)

運行 rs.initiate() 後 mongodb 副本集錯誤“...replSetHeartbeat 需要身份驗證...” (mongodb replica set error "...replSetHeartbeat requires authentication..." after running rs.initiate())

將 mongo shell 連接到受限的 MongoDB Atlas 數據庫? (Connect mongo shell to restricted MongoDB Atlas Database?)

[MongoDB]:更改所有數組字段中的值類型 ([MongoDB]: Changing the type of values in all array fields)







留言討論