如何从数组中获取单个项并将其显示为对象?而不是作为数组Mongodb

如何从数组中获取单个项并将其显示为对象?而不是作为数组Mongodb,mongodb,mongodb-query,nosql,aggregation-framework,Mongodb,Mongodb Query,Nosql,Aggregation Framework,我有一个需要特定对象的集合,例如作为对象而不是数组的notes.blok2和notes.curse5 { "year":2020, "grade":4, "seccion":"A", "id": 100, "name": "pedro", "notes":[{"curse":5,

我有一个需要特定对象的集合,例如作为对象而不是数组的
notes.blok2
notes.curse5

{
  "year":2020,
  "grade":4,
  "seccion":"A",
    "id": 100,
  "name": "pedro",
  "notes":[{"curse":5, 
          "block":1, 
          "score":{ "a1": 5,"a2": 10, "a3": 15} 
          },{"curse":5, 
          "block":2, 
          "score":{ "b1": 10,"b2": 20, "b3": 30} 
          }
   ]
}
我的查询

notas.find({
"$and":[{"grade":1},{"seccion":"A"},{"year":2020}]},
{"projection":{ "grade":1, "seccion":1,"name":1,"id":1,
"notes":{"$elemMatch":{"block":2,"curse":5}},"notes.score":1} })
它可以工作,但返回的注释类似于数组

{
  "_id": "55",
  "id": 100,
  "grade": 5,
  "name": "pedro",
  "seccion": "A",
  "notes": [
    {"score": { "b1": 10,"b2": 20, "b3": 30} }
  ]
}
但我需要这样:
score
与其他人处于同一级别,如果不存在,则显示空的
“score”:{}

{
  "year":2020,
  "grade":5,
  "seccion":"A",
    "id": 100,
  "name": "pedro",
  "score":{ "b1": 10,"b2": 20, "b3": 30} 
}
演示-

您可以使用聚合查询

db.collection.aggregate([
  {
    $match: { // filter
      "grade": 1,
      "seccion": "A",
      "year": 2020,
      "notes": {
        "$elemMatch": {
          "block": 2,
          "curse": 5
        }
      }
    }
  },
  { $unwind: "$notes" },  //break into individual documents
  {
    $match: { // match query on individual note
      "notes.block": 2,
      "notes.curse": 5
    }
  },
  {
    $project: { // projection
      "grade": 1,
      "seccion": 1,
      "name": 1,
      "id": 1,
      "score": "$notes.score"
    }
  }
])

更新

演示-

使用


如果您想在未找到匹配项时为分数设置空对象,您可以这样做-

演示-

演示-

您可以使用聚合查询

db.collection.aggregate([
  {
    $match: { // filter
      "grade": 1,
      "seccion": "A",
      "year": 2020,
      "notes": {
        "$elemMatch": {
          "block": 2,
          "curse": 5
        }
      }
    }
  },
  { $unwind: "$notes" },  //break into individual documents
  {
    $match: { // match query on individual note
      "notes.block": 2,
      "notes.curse": 5
    }
  },
  {
    $project: { // projection
      "grade": 1,
      "seccion": 1,
      "name": 1,
      "id": 1,
      "score": "$notes.score"
    }
  }
])

更新

演示-

使用


如果您想在未找到匹配项时为分数设置空对象,您可以这样做-

演示-


我有一个问题B案例,我需要名称和id,即使我没有分数也可以显示分数:{}emptyUpdated@Carlos请检查。请再帮助一个,如果我想从分数中更新一个元素,我可以由谁来做?请帮助我,你可以教我谁可以更新单个分数?请我有一个问题B案例,我需要名称和id,即使我没有分数也可以显示分数:{}emptyUpdated@Carlos请检查。请再帮助一个,如果我想从分数中更新一个元素,我可以由谁来做?请帮助我,你可以教我谁可以更新单个分数?请
  {
    $set: {
      score: {
        $cond: [
          { $size: "$score" }, // check array length
          { $first: "$score" }, // true - take 1st
          { score: {} } // false - set empty object
        ]
      }
    }
  },