將字串轉換成整型的 MongoDB 查詢?


如需將字串轉換為整數,請在 MongoDB 中使用 parseInt()。我們首先建立一個帶有文件的集合 -

> db.demo369.insertOne({"Price":"1000000"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2e32ae06a1609a00aed")
}
> db.demo369.insertOne({"Price":"1747864"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2e92ae06a1609a00aee")
}
> db.demo369.insertOne({"Price":"19548575"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e57e2ee2ae06a1609a00aef")
}

藉助 find() 方法顯示集合中的所有文件 -

> db.demo369.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : "1000000" }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : "1747864" }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : "19548575" }

以下是將字串轉換為整數的查詢 -

> db.demo369.find().forEach( function (d) {
...    d.Price= parseInt(d.Price);
...    db.demo369.save(d);
... });

藉助 find() 方法顯示集合中的所有文件 -

> db.demo369.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : 1000000 }
{ "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : 1747864 }
{ "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : 19548575 }

更新日期: 02-4 月-2020

2KBS

啟動你的 事業

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.