匹配 MongoDB 陣列中的元素?
你可以使用 $or 運算子和 limit(1) 來匹配陣列中的元素。我們首先建立一個包含文件的集合 -
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"},
... {"StudentCountryName" : "UK" , "StudentSkills" : "Java"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423282cba06f46efe9ee2")
}
> db.matchElementInArrayDemo.insertOne(
... {
... "StudentName" : "Chris" ,
... "StudentOtherDetails" :
... [
... {"StudentCountryName" : "AUS" , "StudentSkills" : "PHP"},
... {"StudentCountryName" : "US" , "StudentSkills" : "MongoDB"}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd423412cba06f46efe9ee3")
}這是使用 find() 方法從集合中顯示所有文件的查詢 -
> db.matchElementInArrayDemo.find().pretty();
這會產生以下輸出 -
{
"_id" : ObjectId("5cd423282cba06f46efe9ee2"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
},
{
"StudentCountryName" : "UK",
"StudentSkills" : "Java"
}
]
}
{
"_id" : ObjectId("5cd423412cba06f46efe9ee3"),
"StudentName" : "Chris",
"StudentOtherDetails" : [
{
"StudentCountryName" : "AUS",
"StudentSkills" : "PHP"
},
{
"StudentCountryName" : "US",
"StudentSkills" : "MongoDB"
}
]
}以下是 MongoDB 中匹配陣列元素的查詢 -
> db.matchElementInArrayDemo.find( { $or : [ {"StudentOtherDetails.StudentCountryName": "US" } ,{"StudentOtherDetails.StudentSkills": "MongoDB" } ] } ).limit(1);這會產生以下輸出 -
{ "_id" : ObjectId("5cd423282cba06f46efe9ee2"), "StudentName" : "Chris", "StudentOtherDetails" : [ { "StudentCountryName" : "US", "StudentSkills" : "MongoDB" }, { "StudentCountryName" : "UK", "StudentSkills" : "Java" } ] }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C #
MongoDB
MySQL
Javascript
PHP