如何篩選 MongoDB 中的陣列元素?


你可以在 MongoDB 中使用 $setIntersection 運算子和聚合框架來篩選陣列元素。首先建立一個帶有文件的集合 -

> db.filterArrayElementsDemo.insertOne( { "Scores": [10,45,67,78,90,98,99,92] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2d582b64f4b851c3a13c8")
}

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

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

這會產生以下輸出 -

{
   "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"),
   "Scores" : [
      10,
      45,
      67,
      78,
      90,
      98,
      99,
      92
   ]
}

以下是對陣列元素進行篩選的查詢 -

> db.filterArrayElementsDemo.aggregate([
...    { $match : {
...          _id: ObjectId("5cd2d582b64f4b851c3a13c8")
...    }},
...    { $project: {
...       Scores: {
...          $setIntersection: ['$Scores', [10,98,99]]
...       }
...    }}
... ]);

這會產生以下輸出 -

{ "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores" : [ 10, 98, 99 ] }

更新於: 2019-07-30

269 瀏覽量

開啟你的 職業生涯

完成課程即可獲得證書

入門
Advertisement
© . All rights reserved.