MongoDB 查詢以選擇具有給定鍵的記錄?


要選擇具有給定鍵的記錄,可以使用 $exists 運算子。語法如下−

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

為了理解上述語法,我們使用文件建立一個集合。使用文件建立集合的查詢如下−

> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentMathMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7be780f10143d8431e0f")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Carol","StudentMathMarks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7bfc80f10143d8431e10")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentAge":26,"StudentMathMarks":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7c1280f10143d8431e11")
}
> db.selectRecordsHavingKeyDemo.insertOne({"StudentName":"Sam","StudentMathMarks":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8b7c2180f10143d8431e12")
}

藉助 find() 方法從集合中顯示所有文件。查詢如下−

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

以下是輸出−

{
   "_id" : ObjectId("5c8b7be780f10143d8431e0f"),
   "StudentName" : "John",
   "StudentAge" : 21,
   "StudentMathMarks" : 78
}
{
   "_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
   "StudentName" : "Carol",
   "StudentMathMarks" : 89
}
{
   "_id" : ObjectId("5c8b7c1280f10143d8431e11"),
   "StudentName" : "Sam",
   "StudentAge" : 26,
   "StudentMathMarks" : 89
}
{
   "_id" : ObjectId("5c8b7c2180f10143d8431e12"),
   "StudentName" : "Sam",
   "StudentMathMarks" : 98
}

下面是選擇具有給定鍵的記錄的查詢−

> db.selectRecordsHavingKeyDemo.find( { StudentMathMarks : { $exists : true } } ).pretty();

以下是輸出−

{
   "_id" : ObjectId("5c8b7be780f10143d8431e0f"),
   "StudentName" : "John",
   "StudentAge" : 21,
   "StudentMathMarks" : 78
}
{
   "_id" : ObjectId("5c8b7bfc80f10143d8431e10"),
   "StudentName" : "Carol",
   "StudentMathMarks" : 89
}
{
   "_id" : ObjectId("5c8b7c1280f10143d8431e11"),
   "StudentName" : "Sam",
   "StudentAge" : 26,
   "StudentMathMarks" : 89
}
{
   "_id" : ObjectId("5c8b7c2180f10143d8431e12"),
   "StudentName" : "Sam",
   "StudentMathMarks" : 98
}

更新於:30-Jul-2019

128 個瀏覽

開啟你的 職業生涯

完成課程獲得證書

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