如何在 MongoDB 中透過整數陣列搜尋文件?


對此,您可以使用 $where 運算子。我們首先使用文件建立一個集合 -

>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"John","StudentScores":[45,78,89,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a219345990cee87fd88c")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Larry","StudentScores":[45,43,34,33]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a22a345990cee87fd88d")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"Chris","StudentScores":[]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a23c345990cee87fd88e")
}
>db.searchDocumentArrayIntegerDemo.insertOne({"StudentFirstName":"David","StudentScores":[99]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2a24d345990cee87fd88f")
}

以下是對集合中所有文件顯示查詢,採用 find() 方法 -

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

將會產生以下輸出 -

{
   "_id" : ObjectId("5cd2a219345990cee87fd88c"),
   "StudentFirstName" : "John",
   "StudentScores" : [
      45,
      78,
      89,
      90
   ]
}
{
   "_id" : ObjectId("5cd2a22a345990cee87fd88d"),
   "StudentFirstName" : "Larry",
   "StudentScores" : [
      45,
      43,
      34,
      33
   ]
}
{
   "_id" : ObjectId("5cd2a23c345990cee87fd88e"),
   "StudentFirstName" : "Chris",
   "StudentScores" : [ ]
}
{
   "_id" : ObjectId("5cd2a24d345990cee87fd88f"),
   "StudentFirstName" : "David",
   "StudentScores" : [
      99
   ]
}

情況 1 - 陣列中包含至少一個值時的查詢 -

> db.searchDocumentArrayIntegerDemo.find({ $where: "this.StudentScores.length >= 1" } );

將會產生以下輸出 -

{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentFirstName" : "John", "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentFirstName" : "Larry", "StudentScores" : [ 45, 43, 34, 33 ] }
{ "_id" : ObjectId("5cd2a24d345990cee87fd88f"), "StudentFirstName" : "David", "StudentScores" : [ 99 ] }

情況 2 - 陣列中包含所有文件中的一個通用值時的查詢 -

> db.searchDocumentArrayIntegerDemo.find({StudentScores: 45}, {StudentScores:1});

將會產生以下輸出 -

{ "_id" : ObjectId("5cd2a219345990cee87fd88c"), "StudentScores" : [ 45, 78, 89, 90 ] }
{ "_id" : ObjectId("5cd2a22a345990cee87fd88d"), "StudentScores" : [ 45, 43, 34, 33 ] }

更新日期: 30-Jul-2019

267 次瀏覽

開啟您的 職業

透過完成課程獲取認證

開始吧
廣告
© . All rights reserved.