如何使用 MongoDB 過濾子文件中的陣列?


在應用匹配之前,可以使用 aggregate 和 unwind 展開陣列列表。為了理解上述概念,讓我們建立一個包含文件的新集合。建立包含文件的新集合的查詢如下

> db.filterArray.insertOne( { "L": [{ "N":1 }, { "N":2 } , { "N":3 }, { "N":4 }, { "N":5 } ]});

執行上述查詢後,可以看到以下內容

{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d63f2734e98fc0a434aeb")
}

使用 find() 方法從集合中顯示文件。查詢如下

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

輸出如下

{
   "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"),
   "L" : [
      {
         "N" : 1
      },
      {
         "N" : 2
      },
      {
         "N" : 3
      },
      {
         "N" : 4
      },
      {
         "N" : 5
      }
   ]
}

以下查詢用於透過 MongoDB 篩選子文件中的陣列。我們使用了 $gt 來獲取大於 3 的欄位

> db.filterArray.aggregate({ $match:{_id:ObjectId("5c6d63f2734e98fc0a434aeb")}}, {
$unwind:'$L'}, {$match:{'L.N':{$gt:3}}},
{$group:{_id:'$_id',subDocument:{$push:'$L.N'}}}).pretty();

輸出如下

{
   "_id" : ObjectId("5c6d63f2734e98fc0a434aeb"),
   "subDocument" : [
      4,
      5
   ]
}

更新於: 2019 年 7 月 30 日

瀏覽次數:346 次

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.