gpt4 book ai didi

mongodb - 如何使用 mongo-template 对数据进行分组

转载 作者:行者123 更新时间:2023-12-04 08:11:51 24 4
gpt4 key购买 nike

我必须根据条件过滤数据并设置字段 isObtained对或错。然后我试图根据字段 grade 对数据进行分组.这是我的数据:

{
"school": "xyz",
"studentName": "John Doe",
"grade": "first",
"Hobbies": [
"Painting",
"Singing"
],
"language": [
"English"
],
"sport": "Badminton",
"totalStudyHours": 85
},
{
"school": xyz,
"studentName": "Jane Doe",
"grade": "third",
"Hobbies": [
"Painting",

],
"language": [
"Spanish"
],
"sport": "Karate",
"totalStudyHours": 65
},
{
"school": "xyz",
"studentName": "joey",
"grade": "first",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Cricket",
"totalStudyHours": 75,
"ispassed": true,

},
{
"studentName": "jason",
"grade": "third",
"Hobbies": [
"Painting",

],
"language": [
"English",
"Spanish"
],
"sport": "Tennis",
"totalStudyHours": 95,
"isObtained": true
},
{
"studentName": "mike",
"grade": "third",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Badminton",
"totalStudyHours": 70,
"isObtained": true
}
预期的输出是
[
{
"grade": "first",
"values": [
{
"studentName": "John Doe",
"grade": "first",
"Hobbies": [
"Painting",
"Singing"
],
"language": [
"English"
],
"sport": "Badminton",
"totalStudyHours": 85,
"isObtained": true
},
{
"studentName": "joey",
"grade": "first",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Cricket",
"totalStudyHours": 75,
"isObtained": true
}
]
},
{
"grade": "third",
"values": [
{
"studentName": "jason",
"grade": "third",
"Hobbies": [
"Painting",

],
"language": [
"English",
"Spanish"
],
"sport": "Tennis",
"totalStudyHours": 95,
"isObtained": true
},
{
"studentName": "mike",
"grade": "third",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Badminton",
"totalStudyHours": 70,
"isObtained": true
}
]
}
]
在 mongoDb 查询中, isObtained字段是根据我们想要的字段设置的。例如,如果我们想要运动记录为“羽毛球”,那么 isObtained当运动是羽毛球时,field 为真,否则为假。
这是查询,但我在基于 grade 分组时遇到问题.
db.students.aggregate([
{
"$match": {
"$and": [
{
"school": "xyz"
}
]
}
},
{
"$project": {
"sport": 1,
"language": 1,
"hobbies": 1,
"isObtained": {
"$and": [
{
"$eq": [
"$sport",
"Badminton"
]
}
]
}
}
}

最佳答案

  • $match您的条件
  • $group按等级并在 values 中制作根文档数组,
  • 定义必填字段并检查条件创建的字段 isObtained如果 sportBadminton则为真否则为假
  • db.students.aggregate([
    { $match: { school: "xyz" } },
    {
    $group: {
    _id: "$grade",
    values: {
    $push: {
    sport: "$sport",
    language: "$language",
    Hobbies: "$Hobbies",
    isObtained: {
    $cond: [{ $eq: ["$sport", "Badminton"] }, true, false]
    }
    }
    }
    }
    }
    ])
    Playground

    如果您想采用动态方法,请尝试 $mergeObjects$$ROOT ,
    Playground

    关于mongodb - 如何使用 mongo-template 对数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65914720/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com