處理 MongoDB 中的可選/空資料?
為了處理空資料,可以使用 $ne 運算子。讓我們用文件建立一個集合。以下是查詢
>db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John","StudentCountryName":""}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cbd5ca629b87623db1b12") } >db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John","StudentCountryName":null}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cbd6ba629b87623db1b13") } > db.handlingAndEmptyDataDemo.insertOne({"StudentName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9cbd71a629b87623db1b14") }
以下是使用 find()方法從集合中顯示所有文件的查詢
> db.handlingAndEmptyDataDemo.find().pretty();
這將生成以下輸出
{ "_id" : ObjectId("5c9cbd5ca629b87623db1b12"), "StudentName" : "John", "StudentCountryName" : "" } { "_id" : ObjectId("5c9cbd6ba629b87623db1b13"), "StudentName" : "John", "StudentCountryName" : null } { "_id" : ObjectId("5c9cbd71a629b87623db1b14"), "StudentName" : "John" }
以下是使用 $ne 處理空資料的查詢
> db.handlingAndEmptyDataDemo.find({StudentCountryName: {$ne: null}});
這將生成以下輸出
{ "_id" : ObjectId("5c9cbd5ca629b87623db1b12"), "StudentName" : "John", "StudentCountryName" : "" }
廣告