嵌套模式/子文档对象中的猫鼬 findById() - 聚合
Posted
技术标签:
【中文标题】嵌套模式/子文档对象中的猫鼬 findById() - 聚合【英文标题】:Mongoose findById() in an object of nested schemas / subdocuments - aggregation 【发布时间】:2021-07-22 13:05:32 【问题描述】:我有一个对象types
。它包含多个模式。我需要通过 id 找到一个项目,但该项目可能在 exampleOne
或 exampleTwo
中(注意:将使用两个以上的模式)。
例如,在此查询"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】:演示 - 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
])
【讨论】:
我相信$match
里面的$or
是不必要的-mongoplayground.net/p/sFEZp6yQdK8
@Sour_Tooth 是的,我的错以上是关于嵌套模式/子文档对象中的猫鼬 findById() - 聚合的主要内容,如果未能解决你的问题,请参考以下文章