이를 위해 중첩된 개체를 쿼리하는 데 사용되는 $elemMatch를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo444.insertOne(
... {
... "Information": [{
... id:1,
... Name:"Chris"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:2,
... Name:"David"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
... {
... "Information": [{
... id:3,
... Name:"Bob"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo444.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] } 다음은 배열의 다중 키 인덱스를 사용하여 쿼리를 개선하는 쿼리입니다 -
> db.demo444.find({
... "Information":{
... $elemMatch:{
... id:2,
... Name:"David"
... }
... }
... }) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }