如何根據欄位不存在來查詢 MongoDB 中的文件?


根據欄位不存在來查詢 MongoDB 中的文件,語法如下 −

db.yourCollectionName.find({ "yourFieldName" : { "$exists" : false } }).pretty();

為了理解上面的語法,讓我們建立一個包含文件的集合。建立包含文件的集合的查詢如下 −

> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"John","StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a5c629064dcd4a68b70e8")
}
> db.findDocumentNonExistenceFieldDemo.insertOne({"StudentName":"David","StudentAge":26,"StudentMathMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a5c809064dcd4a68b70e9")
}

使用 find() 方法顯示集合中的所有文件。查詢如下 −

> db.findDocumentNonExistenceFieldDemo.find().pretty();

以下是輸出 −

{
   "_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
   "StudentName" : "John",
   "StudentAge" : 25
}
{
   "_id" : ObjectId("5c8a5c809064dcd4a68b70e9"),
   "StudentName" : "David",
   "StudentAge" : 26,
   "StudentMathMarks" : 78
}

以下是如何根據欄位不存在來查詢文件的查詢 −

> db.findDocumentNonExistenceFieldDemo.find({ "StudentMathMarks" : { "$exists" : false } }).pretty();

以下是輸出 −

{
   "_id" : ObjectId("5c8a5c629064dcd4a68b70e8"),
   "StudentName" : "John",
   "StudentAge" : 25
}

更新時間: 2019 年 7 月 30 日

75 次瀏覽

啟動您的 職業

完成課程獲取認證

開始
廣告