我有以下模式
{
question: String,
answer: Number,
option1: String,
option2: String,
option3: String,
option4: String,
subject: String,
chapter: String,
topic: String,
subtopic: String,
tags: { type: Array, default: [] },
difficulty: String,
media: { type: String, default: "" }
}我想从这个问题模式创建一个索引,其中索引中的唯一条目可以通过元组(主题、章节、主题、子主题)来标识。
{
"subject": {
"chapter": {
"topic": ["subtopics"],
"topic": ["subtopics"],
},
"chapter": {
"topic": ["subtopics"],
"topic": ["subtopics"],
},
},
"subject": {
"chapter": {
"topic": ["subtopics"],
"topic": ["subtopics"],
},
"chapter": {
"topic": ["subtopics"],
"topic": ["subtopics"],
},
},
}为了达到上面的结果,我一直在尝试一些聚合,到目前为止我已经能够达到目的了。
{
"subject": ["chapters"],
"subject": ["chapters"],
"subject": ["chapters"],
"subject": ["chapters"],
}跟随管道在猫鼬中的应用
{
$group: {
_id: "$subject",
chapters: { $push: "$chapter" }
}
},
{
$group: {
_id: null,
chapters: { $push: { "k": "$_id", "v": "$chapters" } }
}
},
{
$replaceRoot: { "newRoot": { "$arrayToObject": "$chapters" } }
}当我试图扩展上述逻辑以包含主题和子主题时,使用
{
$group: {
_id: "$subject",
chapters: { $push: { "k": "$chapter", "v": { topic: "$topic", subtopic: "$subtopic" } } }
}
},
{
$group: {
_id: null,
chapters: { $push: { "k": "$_id", "v": { "$arrayToObject": "$chapters" } } }
}
},
{
$replaceRoot: { "newRoot": { "$arrayToObject": "$chapters" } }
}我得到以下输出
{
"subject": {
"chapter": {
"topic": "value",
"subtopic": "value"
},
"chapter": {
"topic": "value",
"subtopic": "value"
},
},
"subject": {
"chapter": {
"topic": "value",
"subtopic": "value"
},
"chapter": {
"topic": "value",
"subtopic": "value"
},
},
}

问题是,章节是最后一个主题和子主题的对象,只有,我知道我在哪里犯了错误,但我不知道如何解决它。
发布于 2020-01-24 15:51:08
您可以使用这种主要利用$objectToArray的聚合,但是数据重组并不那么优雅:
db.collection.aggregate(
[
{
"$group" : {
"_id" : {
"subject" : "$subject",
"chapter" : "$chapter",
"topic" : "$topic"
},
"topics" : {
"$push" : "$subtopic"
}
}
},
{
"$addFields" : {
"topic" : {
"k" : "$_id.topic",
"v" : "$topics"
}
}
},
{
"$group" : {
"_id" : {
"subject" : "$_id.subject",
"chapter" : "$_id.chapter"
},
"topics" : {
"$push" : "$topic"
}
}
},
{
"$addFields" : {
"topics" : {
"$arrayToObject" : "$topics"
}
}
},
{
"$addFields" : {
"chapters" : [
{
"k" : "$_id.chapter",
"v" : "$topics"
}
]
}
},
{
"$addFields" : {
"chapters" : {
"$arrayToObject" : "$chapters"
}
}
},
{
"$group" : {
"_id" : null,
"subject" : {
"$push" : {
"k" : "$_id.subject",
"v" : "$chapters"
}
}
}
},
{
"$project" : {
"final" : {
"$arrayToObject" : "$subject"
}
}
},
{
"$replaceRoot" : {
"newRoot" : "$final"
}
}
]);https://stackoverflow.com/questions/59884992
复制相似问题