在 MongoDB 中查詢 null 值?
要在 MongoDB 中查詢 null 值,請使用 $ne 運算子。我們首先使用文件建立一個集合 -
> db.queryingNullDemo.insertOne( ... { ... "StudentName":"Larry", ... "StudentDetails": ... { ... "StudentAge":21, ... "StudentSubject":"MongoDB" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd00bec588d4a6447b2e05f") } > db.queryingNullDemo.insertOne( ... { ... "StudentName":"Sam", ... "StudentDetails": ... { ... "StudentAge":23, ... "StudentSubject":null ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd00c00588d4a6447b2e060") }
使用 find() 方法從集合顯示所有文件的查詢如下 -
> db.queryingNullDemo.find().pretty();
這將生成以下輸出 -
{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"), "StudentName" : "Larry", "StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } } { "_id" : ObjectId("5cd00c00588d4a6447b2e060"), "StudentName" : "Sam", "StudentDetails" : { "StudentAge" : 23, "StudentSubject" : null } }
以下是查詢 null 的方法 -
> db.queryingNullDemo.find({'StudentDetails.StudentSubject': {$ne: null}});
這將生成以下輸出 -
{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"), "StudentName" : "Larry", "StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } }
廣告