logo
Tags down

shadow

mongoose aggregation $group with nested object


By : Shanky Burman
Date : August 01 2020, 05:00 PM
hop of those help? $group can only contain _id or accumulator objects like $first, $last, $sum etc. In your case your building nested object and that syntax is not allowed - accumulator has to be on a top level. You can try two approaches, either return flat structure from $group and then reshape using $project:
code :
{
    $group: {
        _id: '$level',
        level: { $first: '$level' },
        passageId: { $first: '$passageId' },
        userId: { $first: '$userId' },
        type: { $first: '$type' },
        category: { $first: '$category' },
        score: { $first: '$score' },
        completedStage: { $first: '$completedStage' },
        userPassageStatsId_id: { $first: '$_id' },
        readingTime: { $first: '$readingTime' },
        qtdVocab: { $first: '$qtdVocab' },
        qtdTestDone: { $first: '$qtdTestDone' },
        totalQuiz: { $first: '$totalQuiz' },
        progress: { $first: '$progress' }
    }
},
{
    $project: {
        _id: 1,
        level: 1,
        ...,
        userPassageStatsId: {
            _id: "$userPassageStatsId_id",
            stats: {
                readingTime: "$readingTime",
                ...
            }
        }
    }
}
{
    $group: {
        _id: '$level',
        d: { $first: "$$ROOT" }
    }
},
{
    $project: {
        _id: 1,
        level: "$d.level",
        ...,
        userPassageStatsId: {
            _id: "$d._id",
            stats: {
                readingTime: "$d.readingTime",
                ...
            }
        }
    }
}


Share : facebook icon twitter icon

Mongoose group aggregation don't return the rest of fields


By : stark_kid
Date : March 29 2020, 07:55 AM
wish of those help You add them to the $group, but you need to use one of the accumulator operators that determine how you want the multiple values per _id (roomId) to be reduced to a single value.
If you think about it, just adding price: "$price" makes no sense as which price value would you expect it to use?
code :
price: {$first: '$price'} // To use the first price for this roomId (be sure to sort)
price: {$push: '$price'} // To put all of the prices for this roomId into an array
price: [$max: '$price'} // To use the maximum of all the prices for this roomId

How to do mongoose aggregation with nested array documents


By : lassekoo
Date : March 29 2020, 07:55 AM
it helps some times
Since it was the question that you actually asked that was neither really provided in the current acceptance answer, and also that it does some unnecessary things, there is another approach:
code :
var userId = 5; // A variable to work into the submitted pipeline

db.sample.aggregate([
    { "$unwind": "$options" },
    { "$group": {
        "_id": "$_id",
        "my_vote": { "$min": {
            "$cond": [
                { "$setIsSubset": [ [userId], "$options.votes" ] },
                "$options._id",
                false
            ]
        }},
        "options": { "$push": {
            "_id": "$options._id",
            "option": "$options.option",
            "votes": { "$size": "$options.votes" }
        }}
    }}
])
{
    "_id" : ObjectId("5573a0a8b67e246aba2b4b6e"),
    "my_vote" : 2,
    "options" : [
            {
                    "_id" : 1,
                    "option" : "A",
                    "votes" : 3
            },
            {
                    "_id" : 2,
                    "option" : "B",
                    "votes" : 1
            },
            {
                    "_id" : 3,
                    "option" : "C",
                    "votes" : 0
            }
    ]
}
db.sample.aggregate([
    { "$project": {
        "my_vote": {
            "$setDifference": [
                { "$map": {
                    "input": "$options",
                    "as": "o",
                    "in": { "$cond": [
                        { "$setIsSubset": [ [userId], "$$o.votes" ] },
                        "$$o._id",
                        false
                    ]}
                }},
                [false]
            ]
        },
        "options": { "$map": {
            "input": "$options",
            "as": "o",
            "in": {
                "_id": "$$o._id",
                "option": "$$o.option",
                "votes": { "$size": "$$o.votes" }
            }
        }}
    }}
])
{
    "_id" : ObjectId("5573a0a8b67e246aba2b4b6e"),
    "options" : [
            {
                    "_id" : 1,
                    "option" : "A",
                    "votes" : 3
            },
            {
                    "_id" : 2,
                    "option" : "B",
                    "votes" : 1
            },
            {
                    "_id" : 3,
                    "option" : "C",
                    "votes" : 0
            }
    ],
    "my_vote" : [
            2
    ]
}

How to group over Array elements using Mongoose Aggregation FrameWork


By : allan braga
Date : March 29 2020, 07:55 AM
around this issue So if you are trying to get a result that shows a list of employees who has a certain skill, $unwind might help.
code :
db.emp.aggregate([{$unwind:"$primarySkills"},{$group:{"_id":"$primarySkills", "employees":{$push:"$employeeId"}}}])
{ "_id" : ObjectId("5848c3d599fa37d40a7e7391"), "employees" : [ ObjectId("583f114e1cff44b7ab414dc6"), ObjectId("583f114e1cff44b7ab414dc8") ] }
{ "_id" : ObjectId("5848c3c299fa37d40a7e7390"), "employees" : [ ObjectId("583f114e1cff44b7ab414dc6"), ObjectId("583f114e1cff44b7ab414dc8") ] }
{ "_id" : ObjectId("5838373072d7bab017488ba2"), "employees" : [ ObjectId("583f114e1cff44b7ab414dc6") ] }

Group by user in nested object mongoose


By : user3324347
Date : March 29 2020, 07:55 AM
wish of those help You can achieve this with MongoDB aggregation. First get all the planned missions:
code :
// You have to be in an async function to await like this
const plan = await Planning.find({ start: { $eq: new Date(Number(data["date"])) } });
const plannedMission = [];
plan.forEach(plan => { plannedMissions = [...plannedMissions, ...plan.mission] });

/* The plannedMission array should be something like this:
 [ "missionId1", "missionId2", "missionId3"]
*/
const pipeline = [ 
  { $match: { '_id': { $in: plannedMissions } } },
  { $group: { _id: "$user._id", missions: { $push: "$$ROOT"}  } }, 
];
// You have to be in an async function to await like this
const result = await db.missions.aggregate(pipeline);

/* result is an array object like this:
  [ 
    { "_id" : userId1, "missions" : ['mission1', 'mission2'] },
    { "_id" : userId2, "missions" : ['mission1', 'mission2'] }
   ] 
*/

// If you want to further reduce the result to just a single object, you can do this:
const missionsByUser = {};

result.forEach(res => userByMission[res._id] = res.missions);

/* missionsByUser should be something like this:
  { 
    "userId1": ['mission1', 'mission2'],
    "userId2": ['mission1', 'mission2'] 
  }
*/

Using Mongoose Aggregation to Group By and Calculate Averages


By : Odbayar Tumendembere
Date : March 29 2020, 07:55 AM
wish helps you I've figured out the solution to this.
The problem was my $match declaration. had to be before my $group declaration
shadow
Privacy Policy - Terms - Contact Us © voile276.org