如何篩選 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 ] }
Advertisement
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP