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

时间:2021-04-29 07:17:27

标签: javascript mongodb mongoose mongodb-query aggregation-framework

我有一个对象 types。它包含多个模式。我需要通过它的 id 找到一个项目,但该项目可以在 exampleOneexampleTwo 中(注意:将使用超过两个架构)。

例如,在此查询 "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"
  }
},

理想情况下,该解决方案只需要一次搜索。我对此进行了一些研究,但无法弄清楚如何搜索 types 内的所有对象,而无需为每个架构创建搜索并查看其中是否有任何返回结果。

这是我的模式,如果需要的话:

var MainSchema = new Schema ({
  title: { type: String, required: true, maxlength: 255 },
  types: {
    exampleOne: [exampleOneSchema],
    exampleTwo: [exampleTwoSchema],
  }
});
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},
    },
});

感谢所有帮助!

谢谢,

Sour_Tooth

1 个答案:

答案 0 :(得分:2)

演示 - 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
])