MongoDB에서 필드를 프로젝트하려면 $project를 사용하십시오. 문서로 컬렉션을 만들자 −
> db.demo439.insertOne(
... {
... "Name" : "Chris",
... "MarksInformation" : {
... "Marks1" : 67,
... "Marks2" :45,
... "Marks3" : 78
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e77833abbc41e36cc3caeab")
}
> db.demo439.insertOne(
... {
... "Name" : "David",
... "MarksInformation" : {
... "Marks1" : 50,
... "Marks2" :57,
... "Marks3" : 68
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e77833abbc41e36cc3caeac")
}
> db.demo439.insertOne(
... {
... "Name" : "Bob",
... "MarksInformation" : {
... "Score1" : 65,
... "Score2" :71,
...
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e77833bbbc41e36cc3caead")
} find() 메서드를 사용하여 컬렉션의 모든 문서 표시 -
> db.demo439.find();
이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "MarksInformation" : { "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 } }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "MarksInformation" : { "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 } }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "MarksInformation" : { "Score1" : 65, "Score2" : 71 } } 다음은 프로젝트 필드에 대한 쿼리입니다 -
> db.demo439.aggregate({
... $project: {
... "Name" : 1,
... "Marks1": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks1", 0 ] }, 0 ] },{ $ifNull: [ "$MarksInformation.Score1", 0 ] }, "$MarksInformation.Marks1" ] },
... "Marks2": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks2", 0 ] }, 0 ] }, { $ifNull: [ "$MarksInformation.Score2", 0 ] }, "$MarksInformation.Marks2" ] },
... "Marks3": { $cond: [ { $eq:[ { $ifNull: [ "$MarksInformation.Marks3", 0] }, 0 ] }, { $ifNull: [ "$MarksInformation.Score3", 0 ] }, "$MarksInformation.Marks3" ] }
... }}) 이것은 다음과 같은 출력을 생성합니다 -
{ "_id" : ObjectId("5e77833abbc41e36cc3caeab"), "Name" : "Chris", "Marks1" : 67, "Marks2" : 45, "Marks3" : 78 }
{ "_id" : ObjectId("5e77833abbc41e36cc3caeac"), "Name" : "David", "Marks1" : 50, "Marks2" : 57, "Marks3" : 68 }
{ "_id" : ObjectId("5e77833bbbc41e36cc3caead"), "Name" : "Bob", "Marks1" : 65, "Marks2" : 71, "Marks3" : 0 }