在 MongoDB 中按多個數組元素進行篩選?
為此,可以使用 $elemMatch 運算子。$elemMatch 運算子匹配包含一個數組欄位的文件,該陣列欄位至少包含一個與所有指定查詢條件匹配的元素。我們首先使用文件建立集合 -
> db.filterBySeveralElementsDemo.insertOne( "_id":100, "StudentDetails": [ { "StudentName": "John", "StudentCountryName": "US", }, { "StudentName": "Carol", "StudentCountryName": "UK" } ] } ); { "acknowledged" : true, "insertedId" : 100 } > db.filterBySeveralElementsDemo.insertOne( { "_id":101, "StudentDetails": [ { "StudentName": "Sam", "StudentCountryName": "AUS", }, { "StudentName": "Chris", "StudentCountryName": "US" } ] } ); { "acknowledged" : true, "insertedId" : 101 }
下面是使用 find() 方法顯示集合中所有文件的查詢 -
> db.filterBySeveralElementsDemo.find().pretty();
這將生成以下輸出 -
{ "_id" : 100, "StudentDetails" : [ { "StudentName" : "John", "StudentCountryName" : "US" }, { "StudentName" : "Carol", "StudentCountryName" : "UK" } ] } { "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }
以下是按多個數組元素進行篩選的查詢 -
> db.filterBySeveralElementsDemo.find({ StudentDetails: { $elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }}}).pretty();
這將生成以下輸出 -
{ "_id" : 101, "StudentDetails" : [ { "StudentName" : "Sam", "StudentCountryName" : "AUS" }, { "StudentName" : "Chris", "StudentCountryName" : "US" } ] }
廣告