如何檢查 MongoDB 中是否包含某個欄位?


若要檢視 MongoDB 中是否包含某個欄位,可以使用 $exists 運算子。

為理解上述概念,讓我們使用文件來建立一個集合。建立包含文件的集合的查詢如下 −

> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba4136de59bd9de063a1")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"John","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba4e36de59bd9de063a2")
}
> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Chris","StudentAge":24,"StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba6536de59bd9de063a3")
}

> db.checkFieldExistsOrNotDemo.insertOne({"StudentName":"Robert","StudentAge":21,"StudentCountryName":"UK","StudentHobby":["Teaching","Photography"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92ba9d36de59bd9de063a4")
}

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

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

以下是輸出 −

{ "_id" : ObjectId("5c92ba4136de59bd9de063a1"), "StudentName" : "Larry" }
{
   "_id" : ObjectId("5c92ba4e36de59bd9de063a2"),
   "StudentName" : "John",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c92ba6536de59bd9de063a3"),
   "StudentName" : "Chris",
   "StudentAge" : 24,
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "UK",
   "StudentHobby" : [
      "Teaching",
      "Photography"
   ]
}

以下是查詢,用於檢查 MongoDB 中是否包含某個欄位。

用例 1 − 當某個欄位存在時。

查詢如下 −

> db.checkFieldExistsOrNotDemo.find({ 'StudentHobby' : { '$exists' : true }}).pretty();

以下是輸出 −

{
   "_id" : ObjectId("5c92ba9d36de59bd9de063a4"),
   "StudentName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "UK",
   "StudentHobby" : [
      "Teaching",
      "Photography"
   ]
}

用例 2 − 當某個欄位不存在時。

查詢如下

> db.checkFieldExistsOrNotDemo.find({ 'StudentTechnicalSubject' : { '$exists' : true }}).pretty();

如果某個欄位不存在,將不會有任何輸出。

更新於: 30-Jul-2019

6K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告