Docs Menu
Docs Home
/
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 컬렉션을 만듭니다:

이 페이지는 MongoDB C# 드라이버 에서 MongoCollection.Find() 메서드를 사용해 배열 필드에서 쿼리 작업을 실행하는 예시를 설명합니다.

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

이 페이지는 MongoDB Go DriverCollection.Find 함수를 사용하여 배열 필드에 대한 쿼리 작업 예시를 제공합니다.

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

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

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

이 페이지는 MongoDB Java 동기 드라이버com.mongodb.client.MongoCollection.find 메서드를 사용하여 배열 필드에 대한 쿼리 작업 예시를 제공합니다.

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

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

이 페이지는 PyMongo Python 드라이버에서 메서드를 사용해 배열 필드에서 쿼리 작업을 실행하는 예시를 motor.motor_asyncio.AsyncIOMotorCollection.find 설명합니다.

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

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

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

이 페이지는 MongoDB Perl 드라이버에서 MongoDB::Collection::find() 메서드를 사용해 배열 필드에서 쿼리 작업을 실행하는 예시를 설명합니다.

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

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

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

이 페이지는 PyMongo Python 드라이버에서 pymongo.collection.Collection.find 메서드를 사용해 배열 필드에서 쿼리 작업을 실행하는 예시를 설명합니다.

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

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

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

이 페이지에서는 Collection.find() 메서드를 사용하여 배열 필드에서 수행하는 쿼리 작업의 예시를 제공합니다. 이 메서드는 MongoDB Scala 드라이버 내에 있습니다.

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

db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
[
{ "item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [ 14, 21 ] },
{ "item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [ 14, 21 ] },
{ "item": "paper", "qty": 100, "tags": ["red", "blank", "plain"], "dim_cm": [ 14, 21 ] },
{ "item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [ 22.85, 30 ] },
{ "item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [ 10, 15.25 ] }
]

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

var documents = new[]
{
new BsonDocument
{
{ "item", "journal" },
{ "qty", 25 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "notebook" },
{ "qty", 50 },
{ "tags", new BsonArray { "red", "blank" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "paper" },
{ "qty", 100 },
{ "tags", new BsonArray { "red", "blank", "plain" } },
{ "dim_cm", new BsonArray { 14, 21 } }
},
new BsonDocument
{
{ "item", "planner" },
{ "qty", 75 },
{ "tags", new BsonArray { "blank", "red" } },
{ "dim_cm", new BsonArray { 22.85, 30 } }
},
new BsonDocument
{
{ "item", "postcard" },
{ "qty", 45 },
{ "tags", new BsonArray { "blue" } },
{ "dim_cm", new BsonArray { 10, 15.25 } }
}
};
collection.InsertMany(documents);
docs := []interface{}{
bson.D{
{"item", "journal"},
{"qty", 25},
{"tags", bson.A{"blank", "red"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "notebook"},
{"qty", 50},
{"tags", bson.A{"red", "blank"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "paper"},
{"qty", 100},
{"tags", bson.A{"red", "blank", "plain"}},
{"dim_cm", bson.A{14, 21}},
},
bson.D{
{"item", "planner"},
{"qty", 75},
{"tags", bson.A{"blank", "red"}},
{"dim_cm", bson.A{22.85, 30}},
},
bson.D{
{"item", "postcard"},
{"qty", 45},
{"tags", bson.A{"blue"}},
{"dim_cm", bson.A{10, 15.25}},
},
}
result, err := coll.InsertMany(context.TODO(), docs)
Publisher<Success> insertManyPublisher = collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
collection.insertMany(asList(
Document.parse("{ item: 'journal', qty: 25, tags: ['blank', 'red'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'notebook', qty: 50, tags: ['red', 'blank'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'paper', qty: 100, tags: ['red', 'blank', 'plain'], dim_cm: [ 14, 21 ] }"),
Document.parse("{ item: 'planner', qty: 75, tags: ['blank', 'red'], dim_cm: [ 22.85, 30 ] }"),
Document.parse("{ item: 'postcard', qty: 45, tags: ['blue'], dim_cm: [ 10, 15.25 ] }")
));
await db.inventory.insert_many(
[
{"item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [14, 21]},
{"item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [14, 21]},
{
"item": "paper",
"qty": 100,
"tags": ["red", "blank", "plain"],
"dim_cm": [14, 21],
},
{"item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [22.85, 30]},
{"item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [10, 15.25]},
]
)
await db.collection('inventory').insertMany([
{
item: 'journal',
qty: 25,
tags: ['blank', 'red'],
dim_cm: [14, 21]
},
{
item: 'notebook',
qty: 50,
tags: ['red', 'blank'],
dim_cm: [14, 21]
},
{
item: 'paper',
qty: 100,
tags: ['red', 'blank', 'plain'],
dim_cm: [14, 21]
},
{
item: 'planner',
qty: 75,
tags: ['blank', 'red'],
dim_cm: [22.85, 30]
},
{
item: 'postcard',
qty: 45,
tags: ['blue'],
dim_cm: [10, 15.25]
}
]);
$db->coll("inventory")->insert_many(
[
{
item => "journal",
qty => 25,
tags => [ "blank", "red" ],
dim_cm => [ 14, 21 ]
},
{
item => "notebook",
qty => 50,
tags => [ "red", "blank" ],
dim_cm => [ 14, 21 ]
},
{
item => "paper",
qty => 100,
tags => [ "red", "blank", "plain" ],
dim_cm => [ 14, 21 ]
},
{
item => "planner",
qty => 75,
tags => [ "blank", "red" ],
dim_cm => [ 22.85, 30 ]
},
{
item => "postcard",
qty => 45,
tags => ["blue"],
dim_cm => [ 10, 15.25 ]
}
]
);
$insertManyResult = $db->inventory->insertMany([
[
'item' => 'journal',
'qty' => 25,
'tags' => ['blank', 'red'],
'dim_cm' => [14, 21],
],
[
'item' => 'notebook',
'qty' => 50,
'tags' => ['red', 'blank'],
'dim_cm' => [14, 21],
],
[
'item' => 'paper',
'qty' => 100,
'tags' => ['red', 'blank', 'plain'],
'dim_cm' => [14, 21],
],
[
'item' => 'planner',
'qty' => 75,
'tags' => ['blank', 'red'],
'dim_cm' => [22.85, 30],
],
[
'item' => 'postcard',
'qty' => 45,
'tags' => ['blue'],
'dim_cm' => [10, 15.25],
],
]);
db.inventory.insert_many(
[
{"item": "journal", "qty": 25, "tags": ["blank", "red"], "dim_cm": [14, 21]},
{"item": "notebook", "qty": 50, "tags": ["red", "blank"], "dim_cm": [14, 21]},
{
"item": "paper",
"qty": 100,
"tags": ["red", "blank", "plain"],
"dim_cm": [14, 21],
},
{"item": "planner", "qty": 75, "tags": ["blank", "red"], "dim_cm": [22.85, 30]},
{"item": "postcard", "qty": 45, "tags": ["blue"], "dim_cm": [10, 15.25]},
]
)
client[:inventory].insert_many([{ item: 'journal',
qty: 25,
tags: ['blank', 'red'],
dim_cm: [ 14, 21 ] },
{ item: 'notebook',
qty: 50,
tags: ['red', 'blank'],
dim_cm: [ 14, 21 ] },
{ item: 'paper',
qty: 100,
tags: ['red', 'blank', 'plain'],
dim_cm: [ 14, 21 ] },
{ item: 'planner',
qty: 75,
tags: ['blank', 'red'],
dim_cm: [ 22.85, 30 ] },
{ item: 'postcard',
qty: 45,
tags: ['blue'],
dim_cm: [ 10, 15.25 ] }
])
collection.insertMany(Seq(
Document("""{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }"""),
Document("""{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }"""),
Document("""{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }""")
)).execute()

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동등 조건을 지정하려면 Eq 메서드를 사용해 필터를 구성합니다.

Builders<BsonDocument>.Filter.Eq(<field>, <value>)

<value> 요소의 순서를 포함하여 일치시킬 정확한 배열 입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 eq( <field>, <value>)을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 eq( <field>, <value>)을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field> => <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 [ <field> => <value> ]을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field> => <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 equal( <field>, <value> )을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다.

다음은 필드 tags 값이 정확히 두 개의 요소 "red""blank"이 지정된 순서대로 있는 배열인 모든 문서를 쿼리하는 예제입니다.

db.inventory.find( { tags: ["red", "blank"] } )

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

{ tags: ["red", "blank"] }
정확히 일치하는 쿼리 배열
var filter = Builders<BsonDocument>.Filter.Eq("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{{"tags", bson.A{"red", "blank"}}},
)
FindPublisher<Document> findPublisher = collection.find(eq("tags", asList("red", "blank")));
FindIterable<Document> findIterable = collection.find(eq("tags", asList("red", "blank")));
cursor = db.inventory.find({"tags": ["red", "blank"]})
const cursor = db.collection('inventory').find({
tags: ['red', 'blank']
});
$cursor = $db->coll("inventory")->find( { tags => [ "red", "blank" ] } );
$cursor = $db->inventory->find(['tags' => ['red', 'blank']]);
cursor = db.inventory.find({"tags": ["red", "blank"]})
client[:inventory].find(tags: ['red', 'blank'])
var findObservable = collection.find(equal("tags", Seq("red", "blank")))

대신 배열의 순서나 다른 요소에 관계없이 "red""blank" 요소를 모두 포함하는 배열을 찾으려면 $all 연산자를 사용합니다.

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

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

{ tags: { $all: ["red", "blank"] } }
모든 조건과 일치하는 쿼리 배열
var filter = Builders<BsonDocument>.Filter.All("tags", new[] { "red", "blank" });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{{"$all", bson.A{"red", "blank"}}}},
})
findPublisher = collection.find(all("tags", asList("red", "blank")));
findIterable = collection.find(all("tags", asList("red", "blank")));
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
const cursor = db.collection('inventory').find({
tags: { $all: ['red', 'blank'] }
});
$cursor = $db->coll("inventory")->find( { tags => { '$all' => [ "red", "blank" ] } } );
$cursor = $db->inventory->find(['tags' => ['$all' => ['red', 'blank']]]);
cursor = db.inventory.find({"tags": {"$all": ["red", "blank"]}})
client[:inventory].find(tags: { '$all' => ['red', 'blank'] })
findObservable = collection.find(all("tags", "red", "blank"))

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 { <field>: <value> } 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 Eq 메서드를 사용하여 필터를 구성합니다.

Builders<BsonDocument>.Filter.Eq(<field>, <value>)

<value> 는 일치시킬 요소의 값입니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 eq( <field>, <value>) 필터를 사용합니다. 여기서 value는 요소 값입니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 eq( <field>, <value>) 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 { <field>: <value> } 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 { <field>: <value> } 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 필터를 사용하세요.

{ <field> => <value> } 여기서 값은 요소 값입니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 [ <field> => <value> ] 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 { <field>: <value> } 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 { <field> => <value> } 필터를 사용합니다.

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 <value>이 요소 값인 equal( <field>, <value> ) 필터를 사용합니다.

다음 예시에서는 tags가 요소 중 하나로 "red" 문자열을 포함하는 배열에 해당하는 모든 문서를 쿼리합니다.

db.inventory.find( { tags: "red" } )

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

{ tags: "red" }
여러 조건과 일치하는 쿼리 배열
var filter = Builders<BsonDocument>.Filter.Eq("tags", "red");
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", "red"},
})
findPublisher = collection.find(eq("tags", "red"));
findIterable = collection.find(eq("tags", "red"));
cursor = db.inventory.find({"tags": "red"})
const cursor = db.collection('inventory').find({
tags: 'red'
});
$cursor = $db->coll("inventory")->find( { tags => "red" } );
$cursor = $db->inventory->find(['tags' => 'red']);
cursor = db.inventory.find({"tags": "red"})
client[:inventory].find(tags: 'red')
findObservable = collection.find(equal("tags", "red"))

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다. 예시:

var builder = Builders<BsonDocument>.Filter;
builder.And(builder.Eq(<array field>, <value1>), builder.Lt(<array field>, <value2>));

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다. 예시:

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다. 예시:

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field> => { <operator1> => <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

[ <array field> => [ <operator1> => <value1>, ... ] ]

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field> => { <operator1> => <value1>, ... } }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

and(gte(<array field>, <value1>), lt(<array field>, <value2>) ...)

예를 들어, 다음 작업은 dim_cm 배열에 25보다 큰 값을 가진 요소가 하나 이상 포함되는 모든 문서를 쿼리합니다.

db.inventory.find( { dim_cm: { $gt: 25 } } )

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

{ dim_cm: { $gt: 25 } }
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm", 25);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 25},
}},
})
findPublisher = collection.find(gt("dim_cm", 25));
findIterable = collection.find(gt("dim_cm", 25));
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 25 }
});
$cursor = $db->coll("inventory")->find( { "dim_cm" => { '$gt' => 25 } } );
$cursor = $db->inventory->find(['dim_cm' => ['$gt' => 25]]);
cursor = db.inventory.find({"dim_cm": {"$gt": 25}})
client[:inventory].find(dim_cm: { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm", 25))

배열 요소에 복합 조건을 지정할 때 단일 배열 요소가 이러한 조건을 충족하거나 배열 요소의 모든 조합이 조건을 충족하도록 쿼리를 지정할 수 있습니다.

다음 예시에서는 dim_cm 배열에 일부 조합으로 쿼리 조건을 만족하는 요소가 포함된 문서를 쿼리합니다. 예를 들어, 한 요소는 15보다 큰 조건을 만족하고 다른 요소는 20보다 작은 조건을 만족하거나, 단일 요소가 두 조건을 모두 만족할 수 있습니다.

db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

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

{ dim_cm: { $gt: 15, $lt: 20 } }
복합 필터를 사용한 쿼리 배열
var builder = Builders<BsonDocument>.Filter;
var filter = builder.And(builder.Gt("dim_cm", 15), builder.Lt("dim_cm", 20));
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$gt", 15},
{"$lt", 20},
}},
})
findPublisher = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
findIterable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)));
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
const cursor = db.collection('inventory').find({
dim_cm: { $gt: 15, $lt: 20 }
});
$cursor = $db->coll("inventory")->find(
{ "dim_cm" => { '$gt' => 15, '$lt' => 20 } }
);
$cursor = $db->inventory->find([
'dim_cm' => [
'$gt' => 15,
'$lt' => 20,
],
]);
cursor = db.inventory.find({"dim_cm": {"$gt": 15, "$lt": 20}})
client[:inventory].find(dim_cm: { '$gt' => 15,
'$lt' => 20 })
findObservable = collection.find(and(gt("dim_cm", 15), lt("dim_cm", 20)))

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

다음 예시에서는 dim_cm 배열에($gt) 22 보다 크고 ($lt) 30보다 작은 요소가 하나 이상 포함된 문서를 쿼리합니다.

db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

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

{ dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } }
여러 조건으로 배열 쿼리하기
var filter = Builders<BsonDocument>.Filter.ElemMatch<BsonValue>("dim_cm", new BsonDocument { { "$gt", 22 }, { "$lt", 30 } });
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm", bson.D{
{"$elemMatch", bson.D{
{"$gt", 22},
{"$lt", 30},
}},
}},
})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
findIterable = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
const cursor = db.collection('inventory').find({
dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
});
$cursor = $db->coll("inventory")->find(
{ dim_cm => { '$elemMatch' => { '$gt' => 22, '$lt' => 30 } } }
);
$cursor = $db->inventory->find([
'dim_cm' => [
'$elemMatch' => [
'$gt' => 22,
'$lt' => 30,
],
],
]);
cursor = db.inventory.find({"dim_cm": {"$elemMatch": {"$gt": 22, "$lt": 30}}})
client[:inventory].find(dim_cm: { '$elemMatch' => { '$gt' => 22,
'$lt' => 30 } })
findObservable = collection.find(elemMatch("dim_cm", Document("$gt" -> 22, "$lt" -> 30)))

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

참고

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

다음 예시는 dim_cm 배열의 두 번째 요소가 25보다 큰 모든 문서를 쿼리합니다.

db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

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

{ "dim_cm.1": { $gt: 25 } }
인덱스별 쿼리 배열
var filter = Builders<BsonDocument>.Filter.Gt("dim_cm.1", 25);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"dim_cm.1", bson.D{
{"$gt", 25},
}},
})
findPublisher = collection.find(elemMatch("dim_cm", Document.parse("{ $gt: 22, $lt: 30 }")));
findIterable = collection.find(gt("dim_cm.1", 25));
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
const cursor = db.collection('inventory').find({
'dim_cm.1': { $gt: 25 }
});
$cursor = $db->coll("inventory")->find( { "dim_cm.1" => { '$gt' => 25 } } );
$cursor = $db->inventory->find(['dim_cm.1' => ['$gt' => 25]]);
cursor = db.inventory.find({"dim_cm.1": {"$gt": 25}})
client[:inventory].find('dim_cm.1' => { '$gt' => 25 })
findObservable = collection.find(gt("dim_cm.1", 25))

$size 연산자를 사용하여 요소 수를 기준으로 배열을 쿼리할 수 있습니다. 예를 들어 다음은 tags 배열에 요소가 3개 있는 문서를 선택합니다.

db.inventory.find( { "tags": { $size: 3 } } )

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

{ "tags": { $size: 3 } }
var filter = Builders<BsonDocument>.Filter.Size("tags", 3);
var result = collection.Find(filter).ToList();
cursor, err := coll.Find(
context.TODO(),
bson.D{
{"tags", bson.D{
{"$size", 3},
}},
})
findPublisher = collection.find(size("tags", 3));
findIterable = collection.find(size("tags", 3));
cursor = db.inventory.find({"tags": {"$size": 3}})
const cursor = db.collection('inventory').find({
tags: { $size: 3 }
});
$cursor = $db->coll("inventory")->find( { tags => { '$size' => 3 } } );
$cursor = $db->inventory->find(['tags' => ['$size' => 3]]);
cursor = db.inventory.find({"tags": {"$size": 3}})
client[:inventory].find(tags: { '$size' => 3 })
findObservable = collection.find(size("tags", 3))

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

MongoDB Atlas에서 배열을 쿼리하려면 다음 단계를 따르세요.

1
  1. 이미 표시되어 있지 않은 경우 탐색 모음의 Organizations 메뉴에서 원하는 프로젝트가 포함된 조직을 선택합니다.

  2. 아직 표시되지 않은 경우 내비게이션 바의 Projects 메뉴에서 프로젝트를 선택합니다.

  3. Clusters 페이지가 아직 표시되지 않은 경우 사이드바에서 Database를 클릭합니다.

    클러스터 페이지가 표시됩니다.

2
  1. 샘플 데이터가 포함된 클러스터의 경우 Browse Collections 을 클릭합니다.

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

  3. movies 컬렉션을 선택합니다.

3

배열이 포함된 문서를 쿼리하려면 쿼리 필터 문서를 지정합니다. 쿼리 필터 문서는 쿼리 연산자를 사용하여 검색 조건을 지정합니다. 다음 예시 문서를 사용하여 sample_mflix.movies 컬렉션의 배열 필드를 쿼리할 수 있습니다.

쿼리 필터를 적용하려면 예시 문서를 Filter 검색창에 복사한 후 Apply을 클릭합니다.

배열에 동일성 조건을 지정하려면 쿼리 문서 { <field>: <value> }을 사용합니다. 여기서 <value>은(는) 요소의 순서를 포함하여 조건에 정확하게 일치하는 배열입니다. 다음은 지정된 순서로 ["Action", "Comedy"] 배열을 포함하는 genres 필드가 있는 문서를 찾는 예입니다.

{ genres: ["Action", "Comedy"] }

순서나 배열의 다른 요소에 관계없이 ActionComedy 요소를 모두 포함하는 배열을 찾으려면 $all 연산자를 사용합니다.

{ genres: { $all: ["Action", "Comedy"] } }

배열 필드에 지정된 값을 가진 요소가 하나 이상 포함되어 있는지 쿼리하려면 { <field>: <value> } 필터를 사용하며, 여기서 <value> 은 요소 값입니다.

다음 예시에서는 genres 필드의 요소 중 하나로 Short string 이 포함된 모든 문서를 쿼리합니다.

{ genres: "Short" }

배열 필드의 요소에 조건을 지정하려면 쿼리 필터 문서에서 쿼리 연산자를 사용합니다.

{ <array field>: { <operator1>: <value1>, ... } }

예를 들어, 다음 작업은 $nin 연산자를 사용하여 genres 필드에 Drama 이 포함되지 않은 모든 문서를 쿼리합니다.

{ genres: { $nin: ["Drama"] } }

배열 요소에 복합 조건을 지정할 때 단일 배열 요소가 이러한 조건을 충족하거나 배열 요소의 모든 조합이 조건을 충족하도록 쿼리를 지정할 수 있습니다.

다음 예시에서는 cast 배열에 쿼리 조건을 충족하는 요소가 포함된 문서를 쿼리합니다. 예를 들어, 다음 필터는 $regex$eq 연산자를 사용해 단일 배열 요소가 Olsen에서 끝나며 다른 요소가 Mary-Kate Olsen와(과) 같거나 두 조건을 모두 충족하는 단일 요소가 있는 문서를 반환합니다.

{ cast: { $regex: "Olsen$", $eq: "Mary-Kate Olsen" } }

이 쿼리 필터는 출연진에 Mary-Kate Olsen 가 포함된 영화와 출연진에 Mary-Kate OlsenAshley Olsen 가 모두 포함된 영화를 반환합니다.

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

다음 예제에서는 $elemMatch$ne 연산자를 사용하여 languages 배열에 null이 아니고 English와 같지 않은 요소가 하나 이상 포함된 문서를 쿼리합니다.

{ languages: { $elemMatch: { $ne: null, $ne: "English" } } }

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

참고

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

다음 예시에서는 $ne 연산자를 사용해 countries 배열의 첫 번째 요소가 USA와(과) 같지 않은 모든 문서를 쿼리합니다.

{ "countries.0": { $ne: "USA" }

$size 연산자를 사용하여 요소 수를 기준으로 배열을 쿼리할 수 있습니다. 예를 들어 다음은 genres 배열에 요소가 3개 있는 문서를 선택합니다.

{ genres: { $size: 3 } }

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

돌아가기

내장된 문서