MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Mongoose findById() em um objeto de esquemas/subdocumentos aninhados - agregação


Demonstração - https://mongoplayground.net/p/t5VYdkrL_nC
db.collection.aggregate([
  {
    $match: { // filter the document so uniwnd and group have only 1 record to deal with
      $or: [
        { "types.exampleOne._id": "608a5b290e635ece6828141e" },
        { "types.exampleTwo._id": "608a5b290e635ece6828141e" }
      ]
    }
  },
  {
    $group: {
      _id: "$_id",
      docs: { $first: { "$concatArrays": [ "$types.exampleOne", "$types.exampleTwo" ] } } // join both array into 1 element
    }
  },
  { $unwind: "$docs" }, //  break into individual documents
  {
    $match: { // filter the records
     "docs._id": "608a5b290e635ece6828141e"
    }
  },
  { $replaceRoot: { "newRoot": "$docs" } } // set it to root
])