问题描述
我有一个对象types
.它包含多个模式.我需要通过其 id 找到一个项目,但该项目可以在 exampleOne
或 exampleTwo
中(注意:将使用更多然后两个架构).
I have an object types
. It contains multiple schemas. I need to find an item by its id, but the item could be in exampleOne
or exampleTwo
(Note: More then two schemas will be used).
例如,查询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
中搜索所有对象,而无需为每个模式创建搜索并查看它们中是否有任何返回结果.
Ideally, the solution would only require one search. I did some research on this but couldn't figure out how to search all objects inside types
without creating a search for each schema and seeing if any of them returned a result.
这是我的模式,如果需要的话:
Here are my schemas, if they are needed:
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},
},
});
感谢所有帮助!
谢谢,
酸牙
推荐答案
Demo - 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
])
这篇关于Mongoose findById() 在嵌套模式/子文档的对象中 - 聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!