如何在 MongoDB 中查詢列表欄位?


要了解列表欄位查詢,您還可以建立包含文件的集合。

用於建立包含文件的集合的查詢如下 −

> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[33,40,50,60,70]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9522d316f542d757e2b444")
}
> db.andOrDemo.insertOne({"StudentName":"Larry","StudentScore":[87,67,79,98,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c95230916f542d757e2b445")
}

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

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

以下是輸出 −

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}

以下是列表欄位查詢。

查詢如下 −

> db.andOrDemo.find({"StudentScore":70}).pretty();

以下是輸出

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}

案例 3 − 以下是或列表欄位的查詢。

查詢如下 −

> db.andOrDemo.find({"$or":[ {"StudentScore":60}, {"StudentScore":90}]}).pretty();

示例輸出 −

{
   "_id" : ObjectId("5c9522d316f542d757e2b444"),
   "StudentName" : "Larry",
   "StudentScore" : [
      33,
      40,
      50,
      60,
      70
   ]
}
{
   "_id" : ObjectId("5c95230916f542d757e2b445"),
   "StudentName" : "Larry",
   "StudentScore" : [
      87,
      67,
      79,
      98,
      90
   ]
}

更新於:30-Jul-2019

776 次瀏覽

開始您的 職業生涯

完成課程並獲取認證

開始入門
廣告
© . All rights reserved.