$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" } ] }