문서 메뉴
문서 홈
/
MongoDB 매뉴얼
/ /

임베디드 문서 배열 쿼리하기

이 페이지의 내용

  • 배열에 중첩된 문서 쿼리
  • 문서의 배열에서 필드 쿼리 조건 지정
  • 문서 배열에 여러 조건 지정
  • MongoDB Atlas로 문서 배열 쿼리하기
  • 추가 쿼리 튜토리얼

다음 메서드를 사용하여 MongoDB에서 문서를 쿼리할 수 있습니다:

  • 프로그래밍 언어의 드라이버입니다.

  • MongoDB Atlas UI. 자세히 알아보려면 MongoDB Atlas로 문서 배열 쿼리 를 참조하세요.

  • MongoDB Compass


오른쪽 상단의 언어 선택 드롭다운 메뉴를 사용하여 다음 예제의 언어를 설정하거나 MongoDB Compass를 선택합니다.


이 페이지에서는mongosh 에서 db.collection.find() 메서드를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 제공합니다

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지는 MongoDB Compass를 사용해 중첩된 문서 배열에서 쿼리 작업을 실행하는 예시를 설명합니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoCollection.Find() 를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 제공합니다.MongoDB C# 드라이버 의 메서드 .

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 Collection.Find 를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 제공합니다. MongoDB Go 드라이버 의 함수 .

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoDB Java Reactive Streams 드라이버에서 com.mongodb.reactivestreams.client.MongoCollection.find 메서드를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예시를 보여줍니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoDB Java Synchronous 드라이버에서 com.mongodb.client.MongoCollection.find 메서드를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예시를 보여줍니다.

드라이버는 com.mongodb.client.model.Filters 를 제공합니다. 필터 문서를 쉽게 만들 수 있는 헬퍼 메서드. 이 페이지의 예제에서는 이러한 메서드를 사용하여 필터 문서를 만듭니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 motor.motor_asyncio.AsyncIOMotorCollection.find 제공합니다. 모터 의 메서드 드라이버.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 Collection.find() 메서드를 사용하여 중첩된 문서 배열에서 수행하는 쿼리 작업의 예시를 제공합니다. MongoDB Node.js 드라이버에서 해당 작업을 수행합니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoDB::Collection::find() 메서드 를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 제공합니다.MongoDB 펄(Perl) 드라이버 의 메서드 .

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoDB PHP 라이브러리에서 MongoDB\\Collection::find() 메서드를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예시를 보여줍니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 pymongo.collection.Collection.find 예를 제공합니다. 메서드 를 제공합니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 MongoDB Ruby 드라이버에서 Mongo::Collection#find() 메서드를 사용하여 중첩 문서 배열에 대한 쿼리 작업의 예시를 제공합니다.

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

이 페이지에서는 collection.find() 메서드를 사용하여 중첩된 문서 배열에 대한 쿼리 작업의 예를 제공합니다. MongoDB 스칼라 드라이버 의 메서드 .

이 페이지의 예제에서는 inventory 컬렉션을 사용합니다. MongoDB 인스턴스의 테스트 데이터베이스에 연결한 다음 inventory 컬렉션을 만듭니다:

db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
[
{ "item": "journal", "instock": [ { "warehouse": "A", "qty": 5 }, { "warehouse": "C", "qty": 15 } ] },
{ "item": "notebook", "instock": [ { "warehouse": "C", "qty": 5 } ] },
{ "item": "paper", "instock": [ { "warehouse": "A", "qty": 60 }, { "warehouse": "B", "qty": 15 } ] },
{ "item": "planner", "instock": [ { "warehouse": "A", "qty": 40 }, { "warehouse": "B", "qty": 5 } ] },
{ "item": "postcard", "instock": [ { "warehouse": "B","qty": 15 }, { "warehouse": "C", "qty": 35 } ] }
]

MongoDB Compass에서 문서를 삽입하는 방법은 문서 삽입하기를 참조하세요.

var documents = new[]
{
new BsonDocument
{
{ "item", "journal" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 5 } },
new BsonDocument { { "warehouse", "C" }, { "qty", 15 } } }
}
},
new BsonDocument
{
{ "item", "notebook" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "C" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "paper" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 60 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 15 } } }
}
},
new BsonDocument
{
{ "item", "planner" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "A" }, { "qty", 40 } },
new BsonDocument { { "warehouse", "B" }, { "qty", 5 } } }
}
},
new BsonDocument
{
{ "item", "postcard" },
{ "instock", new BsonArray
{
new BsonDocument { { "warehouse", "B" }, { "qty", 15 } },
new BsonDocument { { "warehouse", "C" }, { "qty", 35 } } }
}
}
};
collection.InsertMany(documents);
docs := []interface{}{
bson.D{
{"item", "journal"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 5},
},
bson.D{
{"warehouse", "C"},
{"qty", 15},
},
}},
},
bson.D{
{"item", "notebook"},
{"instock", bson.A{
bson.D{
{"warehouse", "C"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "paper"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 60},
},
bson.D{
{"warehouse", "B"},
{"qty", 15},
},
}},
},
bson.D{
{"item", "planner"},
{"instock", bson.A{
bson.D{
{"warehouse", "A"},
{"qty", 40},
},
bson.D{
{"warehouse", "B"},
{"qty", 5},
},
}},
},
bson.D{
{"item", "postcard"},
{"instock", bson.A{
bson.D{
{"warehouse", "B"},
{"qty", 15},
},
bson.D{
{"warehouse", "C"},
{"qty", 35},
},
}},
},
}
result, err := coll.InsertMany(context.TODO(), docs)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
collection.insertMany(asList(
Document.parse("{ item: 'journal', instock: [ { warehouse: 'A', qty: 5 }, { warehouse: 'C', qty: 15 } ] }"),
Document.parse("{ item: 'notebook', instock: [ { warehouse: 'C', qty: 5 } ] }"),
Document.parse("{ item: 'paper', instock: [ { warehouse: 'A', qty: 60 }, { warehouse: 'B', qty: 15 } ] }"),
Document.parse("{ item: 'planner', instock: [ { warehouse: 'A', qty: 40 }, { warehouse: 'B', qty: 5 } ] }"),
Document.parse("{ item: 'postcard', instock: [ { warehouse: 'B', qty: 15 }, { warehouse: 'C', qty: 35 } ] }")
));
# Subdocument key order matters in a few of these examples so we have
# to use bson.son.SON instead of a Python dict.
from bson.son import SON
await db.inventory.insert_many(
[
{
"item": "journal",
"instock": [
SON([("warehouse", "A"), ("qty", 5)]),
SON([("warehouse", "C"), ("qty", 15)]),
],
},
{"item": "notebook", "instock": [SON([("warehouse", "C"), ("qty", 5)])]},
{
"item": "paper",
"instock": [
SON([("warehouse", "A"), ("qty", 60)]),
SON([("warehouse", "B"), ("qty", 15)]),
],
},
{
"item": "planner",
"instock": [
SON([("warehouse", "A"), ("qty", 40)]),
SON([("warehouse", "B"), ("qty", 5)]),
],
},
{
"item": "postcard",
"instock": [
SON([("warehouse", "B"), ("qty", 15)]),
SON([("warehouse", "C"), ("qty", 35)]),
],
},
]
)
await db.collection('inventory').insertMany([
{
item: 'journal',
instock: [
{ warehouse: 'A', qty: 5 },
{ warehouse: 'C', qty: 15 }
]
},
{
item: 'notebook',
instock: [{ warehouse: 'C', qty: 5 }]
},
{
item: 'paper',
instock: [
{ warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 15 }
]
},
{
item: 'planner',
instock: [
{ warehouse: 'A', qty: 40 },
{ warehouse: 'B', qty: 5 }
]
},
{
item: 'postcard',
instock: [
{ warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }
]
}
]);
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$db->coll("inventory")->insert_many(
[
{
item => "journal",
instock => [
Tie::IxHash->new( warehouse => "A", qty => 5 ),
Tie::IxHash->new( warehouse => "C", qty => 15 )
]
},
{
item => "notebook",
instock => [ Tie::IxHash->new( warehouse => "C", qty => 5 ) ]
},
{
item => "paper",
instock => [
Tie::IxHash->new( warehouse => "A", qty => 60 ),
Tie::IxHash->new( warehouse => "B", qty => 15 )
]
},
{
item => "planner",
instock => [
Tie::IxHash->new( warehouse => "A", qty => 40 ),
Tie::IxHash->new( warehouse => "B", qty => 5 )
]
},
{
item => "postcard",
instock => [
Tie::IxHash->new( warehouse => "B", qty => 15 ),
Tie::IxHash->new( warehouse => "C", qty => 35 )
]
}
]
);
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'instock' => [
['warehouse' => 'A', 'qty' => 5],
['warehouse' => 'C', 'qty' => 15],
],
],
[
'item' => 'notebook',
'instock' => [
['warehouse' => 'C', 'qty' => 5],
],
],
[
'item' => 'paper',
'instock' => [
['warehouse' => 'A', 'qty' => 60],
['warehouse' => 'B', 'qty' => 15],
],
],
[
'item' => 'planner',
'instock' => [
['warehouse' => 'A', 'qty' => 40],
['warehouse' => 'B', 'qty' => 5],
],
],
[
'item' => 'postcard',
'instock' => [
['warehouse' => 'B', 'qty' => 15],
['warehouse' => 'C', 'qty' => 35],
],
],
]);
# Subdocument key order matters in a few of these examples so we have
# to use bson.son.SON instead of a Python dict.
from bson.son import SON
db.inventory.insert_many(
[
{
"item": "journal",
"instock": [
SON([("warehouse", "A"), ("qty", 5)]),
SON([("warehouse", "C"), ("qty", 15)]),
],
},
{"item": "notebook", "instock": [SON([("warehouse", "C"), ("qty", 5)])]},
{
"item": "paper",
"instock": [
SON([("warehouse", "A"), ("qty", 60)]),
SON([("warehouse", "B"), ("qty", 15)]),
],
},
{
"item": "planner",
"instock": [
SON([("warehouse", "A"), ("qty", 40)]),
SON([("warehouse", "B"), ("qty", 5)]),
],
},
{
"item": "postcard",
"instock": [
SON([("warehouse", "B"), ("qty", 15)]),
SON([("warehouse", "C"), ("qty", 35)]),
],
},
]
)
client[:inventory].insert_many([{ item: 'journal',
instock: [ { warehouse: 'A', qty: 5 },
{ warehouse: 'C', qty: 15 }] },
{ item: 'notebook',
instock: [ { warehouse: 'C', qty: 5 }] },
{ item: 'paper',
instock: [ { warehouse: 'A', qty: 60 },
{ warehouse: 'B', qty: 15 }] },
{ item: 'planner',
instock: [ { warehouse: 'A', qty: 40 },
{ warehouse: 'B', qty: 5 }] },
{ item: 'postcard',
instock: [ { warehouse: 'B', qty: 15 },
{ warehouse: 'C', qty: 35 }] }
])
collection.insertMany(Seq(
Document("""{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }"""),
Document("""{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] }"""),
Document("""{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] }"""),
Document("""{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] }"""),
Document("""{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }""")
)).execute()

다음 예에서는 instock 배열의 요소가 지정된 문서와 일치하는 모든 문서를 선택합니다.

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find 을(를) 클릭합니다.

{ "instock": { warehouse: "A", qty: 5 } }
중첩 배열 요소 쿼리
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "warehouse", "A" }, { "qty", 5 } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"warehouse", "A"},
{"qty", 5},
}},
})
FindPublisher<Document> findPublisher = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
FindIterable<Document> findIterable = collection.find(eq("instock", Document.parse("{ warehouse: 'A', qty: 5 }")));
cursor = db.inventory.find({"instock": SON([("warehouse", "A"), ("qty", 5)])})
const cursor = db.collection('inventory').find({
instock: { warehouse: 'A', qty: 5 }
});
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$cursor = $db->coll("inventory")->find(
{ instock => Tie::IxHash->new( warehouse => "A", qty => 5 ) }
);
$cursor = $db->inventory->find(['instock' => ['warehouse' => 'A', 'qty' => 5]]);
cursor = db.inventory.find({"instock": SON([("warehouse", "A"), ("qty", 5)])})
client[:inventory].find(instock: { warehouse: 'A', qty: 5 })
var findObservable = collection.find(equal("instock", Document("warehouse" -> "A", "qty" -> 5)))

전체 포함/중첩 문서에 관한 동등성 일치는 필드 순서를 포함하여 지정된 문서와의 정확한 일치를 요구합니다. 예를 들어 다음 쿼리는 inventory 컬렉션의 어떤 문서와도 일치하지 않습니다.

db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )
중첩 배열 요소 쿼리
var filter = Builders<BsonDocument>.Filter.AnyEq("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"qty", 5},
{"warehouse", "A"},
}},
})
findPublisher = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
findIterable = collection.find(eq("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
cursor = db.inventory.find({"instock": SON([("qty", 5), ("warehouse", "A")])})
const cursor = db.collection('inventory').find({
instock: { qty: 5, warehouse: 'A' }
});
# Subdocument key order matters in this example so we have
# to use Tie::IxHash instead of a regular, unordered Perl hash.
$cursor = $db->coll("inventory")->find(
{ instock => Tie::IxHash->new( qty => 5, warehouse => "A" ) }
);
$cursor = $db->inventory->find(['instock' => ['qty' => 5, 'warehouse' => 'A']]);
cursor = db.inventory.find({"instock": SON([("qty", 5), ("warehouse", "A")])})
client[:inventory].find(instock: { qty: 5, warehouse: 'A' } )
findObservable = collection.find(equal("instock", Document("qty" -> 5, "warehouse" -> "A")))

배열에 중첩된 문서의 인덱스 위치를 알 수 없는 경우 배열 필드의 이름을 중첩된 문서의 점(.) 및 필드 이름과 연결합니다.

다음 예시에서는 instock 배열에서 포함된 문서 중 하나 이상의 qty 필드 값이 20 이하인 경우에 해당하는 모든 문서를 선택합니다.

db.inventory.find( { 'instock.qty': { $lte: 20 } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ 'instock.qty': { $lte: 20 } }
단일 조건과 일치하는 포함된 필드 쿼리
var filter = Builders<BsonDocument>.Filter.Lte("instock.qty", 20);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", bson.D{
{"$lte", 20},
}},
})
findPublisher = collection.find(lte("instock.qty", 20));
findIterable = collection.find(lte("instock.qty", 20));
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})
const cursor = db.collection('inventory').find({
'instock.qty': { $lte: 20 }
});
$cursor = $db->coll("inventory")->find( { 'instock.qty' => { '$lte' => 20 } } );
$cursor = $db->inventory->find(['instock.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({"instock.qty": {"$lte": 20}})
client[:inventory].find('instock.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.qty", 20))

점 표기법을 사용하면 배열의 특정 인덱스 또는 위치에서 문서 필드의 쿼리 조건을 지정할 수 있습니다. 배열은 제로 기반 인덱싱을 사용합니다.

참고

점 표기법을 사용하여 쿼리하는 경우 필드와 인덱스는 따옴표 안에 포함되어야 합니다.

다음 예시에서는 instock 배열이 qty 필드의 값이 20 이하인 문서를 첫 요소로 포함하는 경우에 해당하는 모든 문서를 선택합니다.

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ 'instock.0.qty': { $lte: 20 } }
단일 조건과 일치하는 배열 요소 쿼리
var filter = Builders<BsonDocument>.Filter.Lte("instock.0.qty", 20);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.0.qty", bson.D{
{"$lte", 20},
}},
})
findPublisher = collection.find(lte("instock.0.qty", 20));
findIterable = collection.find(lte("instock.0.qty", 20));
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})
const cursor = db.collection('inventory').find({
'instock.0.qty': { $lte: 20 }
});
$cursor = $db->coll("inventory")->find( { 'instock.0.qty' => { '$lte' => 20 } } );
$cursor = $db->inventory->find(['instock.0.qty' => ['$lte' => 20]]);
cursor = db.inventory.find({"instock.0.qty": {"$lte": 20}})
client[:inventory].find('instock.0.qty' => { '$lte' => 20 })
findObservable = collection.find(lte("instock.0.qty", 20))

문서 배열에 중첩 필드 조건을 하나 이상 지정하는 경우 단일 문서가 이러한 조건을 충족하거나, 단일 문서를 포함하여 배열에 있는 문서 조합이 조건을 충족하도록 쿼리를 지정할 수 있습니다.

$elemMatch 연산자를 사용하여 포함된 문서 배열에 관한 여러 기준을 지정하여 하나 이상의 포함된 문서가 지정된 기준을 모두 충족하도록 합니다.

다음 예시에서는 instock 배열에 qty 필드는 5 와 같고 warehouse 필드는 A와 같은 포함된 문서를 하나 이상 보유한 문서를 쿼리합니다.

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ "instock": { $elemMatch: { qty: 5, warehouse: "A" } } }
여러 조건과 일치하는 단일 문서 쿼리
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", 5 }, { "warehouse", "A" } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"$elemMatch", bson.D{
{"qty", 5},
{"warehouse", "A"},
}},
}},
})
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: 5, warehouse: 'A' }")));
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
const cursor = db.collection('inventory').find({
instock: { $elemMatch: { qty: 5, warehouse: 'A' } }
});
$cursor = $db->coll("inventory")->find(
{ instock => { '$elemMatch' => { qty => 5, warehouse => "A" } } }
);
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => 5, 'warehouse' => 'A']]]);
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": 5, "warehouse": "A"}}})
client[:inventory].find(instock: { '$elemMatch' => { qty: 5,
warehouse: 'A' } })
findObservable = collection.find(elemMatch("instock", Document("qty" -> 5, "warehouse" -> "A")))

다음 예시에서는 instock 배열에 qty 필드가 10보다 크고 20과 같거나 작은 포함 문서를 하나 이상 보유한 문서를 쿼리합니다.

db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } }
여러 조건과 일치하는 단일 문서 쿼리
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("instock", new BsonDocument { { "qty", new BsonDocument { { "$gt", 10 }, { "$lte", 20 } } } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock", bson.D{
{"$elemMatch", bson.D{
{"qty", bson.D{
{"$gt", 10},
{"$lte", 20},
}},
}},
}},
})
findPublisher = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
findIterable = collection.find(elemMatch("instock", Document.parse("{ qty: { $gt: 10, $lte: 20 } }")));
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
const cursor = db.collection('inventory').find({
instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }
});
$cursor = $db->coll("inventory") ->find(
{ instock => { '$elemMatch' => { qty => { '$gt' => 10, '$lte' => 20 } } } }
);
$cursor = $db->inventory->find(['instock' => ['$elemMatch' => ['qty' => ['$gt' => 10, '$lte' => 20]]]]);
cursor = db.inventory.find({"instock": {"$elemMatch": {"qty": {"$gt": 10, "$lte": 20}}}})
client[:inventory].find(instock: { '$elemMatch' => { qty: { '$gt' => 10,
'$lte' => 20 } } })
findObservable = collection.find(elemMatch("instock", Document("""{ qty: { $gt: 10, $lte: 20 } }""")))

배열 필드의 복합 쿼리 조건에 $elemMatch 연산자가 사용되지 않는 경우 쿼리는 배열에 조건을 충족하는 요소 조합이 포함된 문서를 선택합니다.

예를 들어, 다음 쿼리는 instock 배열에 중첩된 문서 중 qty 필드가 10보다 크고 배열에 포함된 문서 중 qty 필드가 20보다 작거나 같은 문서(반드시 동일한 포함 문서일 필요는 없음)를 보유한 문서를 일치시킵니다.

db.inventory.find( { "instock.qty": { $gt: 10, $lte: 20 } } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ "instock.qty": { $gt: 10, $lte: 20 } }
범위 내의 수량 값 쿼리
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("instock.qty", 10), builder.Lte("instock.qty", 20));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", bson.D{
{"$gt", 10},
{"$lte", 20},
}},
})
findPublisher = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
findIterable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)));
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
const cursor = db.collection('inventory').find({
'instock.qty': { $gt: 10, $lte: 20 }
});
$cursor = $db->coll("inventory")->find(
{ "instock.qty" => { '$gt' => 10, '$lte' => 20 } }
);
$cursor = $db->inventory->find(['instock.qty' => ['$gt' => 10, '$lte' => 20]]);
cursor = db.inventory.find({"instock.qty": {"$gt": 10, "$lte": 20}})
client[:inventory].find('instock.qty' => { '$gt' => 10, '$lte' => 20 })
findObservable = collection.find(and(gt("instock.qty", 10), lte("instock.qty", 20)))

다음 예시에서는 instock 배열에 qty 필드가 5와 같은 포함 문서와 warehouse 필드가 A와 같은 포함 문서를 각각 하나 이상 보유하는(반드시 동일한 포함 문서일 필요는 없음) 문서를 쿼리합니다.

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

다음 필터를 Compass 쿼리 표시줄에 복사하고 Find를 클릭합니다.

{ "instock.qty": 5, "instock.warehouse": "A" }
수량 및 창고 위치 일치 쿼리
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Eq("instock.qty", 5), builder.Eq("instock.warehouse", "A"));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"instock.qty", 5},
{"instock.warehouse", "A"},
})
findPublisher = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
findIterable = collection.find(and(eq("instock.qty", 5), eq("instock.warehouse", "A")));
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})
const cursor = db.collection('inventory').find({
'instock.qty': 5,
'instock.warehouse': 'A'
});
$cursor = $db->coll("inventory")->find(
{ "instock.qty" => 5, "instock.warehouse" => "A" }
);
$cursor = $db->inventory->find(['instock.qty' => 5, 'instock.warehouse' => 'A']);
cursor = db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})
client[:inventory].find('instock.qty' => 5,
'instock.warehouse' => 'A')
findObservable = collection.find(and(equal("instock.qty", 5), equal("instock.warehouse", "A")))

이 섹션의 예시에서는 샘플 교육 데이터세트를 사용합니다. MongoDB Atlas 배포에 샘플 데이터세트를 로드하는 방법을 알아보려면 샘플 데이터 로드를 참조하세요.

MongoDB Atlas에서 문서 배열을 쿼리하려면 다음 단계를 수행합니다.

1
  1. MongoDB Atlas UI의 사이드바에서 Database 버튼을 클릭합니다.

  2. 샘플 데이터가 포함된 데이터베이스 배포서버의 경우 Browse Collections을 클릭합니다.

  3. 왼쪽 탐색 창에서 sample_training 데이터베이스를 선택합니다.

  4. grades 컬렉션을 선택합니다.

2

Filter 필드에 쿼리 필터 문서를 지정합니다. 쿼리 필터 문서는 쿼리 연산자를 사용하여 검색 조건을 지정합니다.

다음 쿼리 필터 문서를 Filter 검색 바에 복사합니다.

{"scores.type": "exam"}
3

이 쿼리 필터는 typeexam 로 설정된 scores 배열의 하위 문서를 포함하는 sample_training.grades 컬렉션의 모든 문서를 반환합니다. 전체 scores 배열을 포함한 전체 문서가 반환됩니다. 반환된 배열을 수정하는 방법에 대한 자세한 내용은 반환된 배열에 특정 배열 요소 프로젝트하기를 참조하세요.

추가 쿼리 예시는 아래에서 확인 가능합니다.

돌아가기

배열 쿼리

다음

쿼리에서 반환할 프로젝트 필드