Javascript 嵌套模式/子文档对象中的Mongoose findById()-聚合

Javascript 嵌套模式/子文档对象中的Mongoose findById()-聚合,javascript,mongodb,mongoose,mongodb-query,aggregation-framework,Javascript,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有一个对象类型。它包含多个模式。我需要根据其id查找项目,但该项目可能位于exampleOne或exampleotwo中(注意:将使用两个以上的模式) 例如,在此服务器上查询“id:608a5b290e635ece6828141e”: { "_id": "608642db80a36336946620aa", "title": "titleHere", "types": { &

我有一个对象
类型
。它包含多个模式。我需要根据其id查找项目,但该项目可能位于
exampleOne
exampleotwo
中(注意:将使用两个以上的模式)

例如,在此服务器上查询
“id:608a5b290e635ece6828141e”

{
  "_id": "608642db80a36336946620aa",
  "title": "titleHere",
  "types": {
    "exampleOne": [
      {
        "_id": "6086430080a36336946620ab",
        "front": "front",
        "back": "back"
      },
      {
        "_id": "608a5b186ee1598ac9c222b4",
        "front": "front2",
        "back": "back2"
      }
    ],
    "exampleTwo": [
      {
        "_id": "608a5b290e635ece6828141e", // the queried document
        "normal": {
          "front": "2front",
          "back": "2back"
        },
        "reversed": {
          "front": "2frontReversed",
          "back": "2backReversed"
        }
      },
      {
        "_id": "608a5b31a3f9806de2537269",
        "normal": {
          "front": "2front2",
          "back": "2back2"
        },
        "reversed": {
          "front": "2frontReversed2",
          "back": "2backReversed2"
        }
      }
    ]
  }
}
应返回:

{
  "_id": "608a5b290e635ece6828141e",
  "normal": {
    "front": "2front",
    "back": "2back"
  },
  "reversed": {
    "front": "2frontReversed",
    "back": "2backReversed"
  }
},
理想情况下,解决方案只需要一次搜索。我对此做了一些研究,但不知道如何搜索
类型
中的所有对象,而不为每个模式创建搜索并查看其中是否有返回结果

以下是我的模式(如果需要):

var MainSchema = new Schema ({
  title: { type: String, required: true, maxlength: 255 },
  types: {
    exampleOne: [exampleOneSchema],
    exampleTwo: [exampleTwoSchema],
  }
});
感谢您的帮助

谢谢

酸牙

演示-


我相信
$or
里面的
$match
是不必要的-酸牙是的,我的坏牙
var exampleOneSchema = new Schema({
    front: {type: String, required: true},
    back: {type: String, required: true},
});
var exampleTwoSchema= new Schema({
    normal: {
      front: {type: String, required: true},
      back: {type: String, required: true},
    },
    reversed: {
      front: {type: String, required: true},
      back: {type: String, required: true},
    },
});
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
])