범위를 기반으로 포함된 문서 배열을 쿼리하려면 집계()를 사용합니다. 문서로 컬렉션을 만들자 −
> db.demo346.insertOne(
... {
... _id: 101,
... userDetails: [
... { UserName: "Chris", Score:78},
... { UserName: "David", Score:68},
... { UserName: "Bob", Score:88}
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo346.insertOne(
... {
... _id: 102,
... userDetails: [
... { UserName: "Mike", Score:92},
... { UserName: "Sam", Score:62},
... { UserName: "Carol", Score:97}
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 } find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo346.find();
이것은 다음과 같은 출력을 생성합니다 -
{
"_id" : 101, "userDetails" : [
{ "UserName" : "Chris", "Score" : 78 },
{ "UserName" : "David", "Score" : 68 },
{ "UserName" : "Bob", "Score" : 88 }
]
}
{
"_id" : 102, "userDetails" : [
{ "UserName" : "Mike", "Score" : 92 },
{ "UserName" : "Sam", "Score" : 62 },
{ "UserName" : "Carol", "Score" : 97 }
]
} 다음은 Range −
를 기반으로 MongoDB에 포함된 문서 배열을 쿼리하는 방법입니다.> db.demo346.aggregate([
... { "$match": { "$expr": { "$gte": [{ "$size": { "$ifNull": ["$userDetails", []] } }, 1] }}},
... { "$addFields": {
... "userDetails": {
... "$filter": {
... "input": { "$ifNull": ["$userDetails", []] },
... "cond": {
... "$and": [
... { "$gte": ["$$this.Score", 80] },
... { "$lte": ["$$this.Score", 99] }
... ]
... }
... }
... }
... }}
... ]) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : 101, "userDetails" : [ { "UserName" : "Bob", "Score" : 88 } ] }
{ "_id" : 102, "userDetails" : [ { "UserName" : "Mike", "Score" : 92 }, { "UserName" : "Carol", "Score" : 97 } ] }