如何将$ replaceroot添加到我的aggregate.group函数

时间:2019-01-22 07:59:11

标签: mongoose

我正在使用聚合函数对所有元素进行分组,但是我不知道如何对它们执行替换根。我在猫鼬文档中没有找到它,猫鼬支持它。下面是我的代码。

var MessageODM = mongoose.model('message', new Message());

exports.save = function (message, callback) {

    new MessageODM(message).save();

};
exports.getUnreadChat = function (user, callback) {

    MessageODM().aggregate([
        {
            $match: { 'receiver.email': user.email}

        }])
        .sort({ dateCreated: 'desc'})
        .group({ _id: { sender: '$sender', receiver: '$receiver' },children: {$push: '$$ROOT'} })]
        .exec(callback);

};

我正在尝试用索引中的第一个替换子代的值。
在我为Java编写的汇总函数中,我是通过

实现的
MatchOperation matchOperation = match(
            Criteria.where("receiver.email").is(receiver.getEmail())
                    .andOperator(Criteria.where("isRead").is(false)));


    SortOperation sortOperation = new SortOperation(new Sort(Sort.Direction.DESC,"dateCreated"));

    GroupOperation groupOperation = group("sender","receiver").push("$$ROOT").as("children");

    AggregationOperation replaceRoot = Aggregation.replaceRoot().withValueOf(ArrayOperators.ArrayElemAt.arrayOf("children").elementAt(0));



    Aggregation aggregation = newAggregation(matchOperation, sortOperation, groupOperation,replaceRoot);


    AggregationResults<Message> result = mongoTemplate.aggregate(aggregation,"message", Message.class);


    return result.getMappedResults();

纯mongDb的while和替代将是这样的:

    db.getCollection('contentSource').aggregate( [ { $sort: { "modified": -1 } }, 
{ $group: { _id: "$sourceId", cs: { $push: "$$ROOT" } }}, 
{ $replaceRoot: { newRoot: { $arrayElemAt: ['$cs', 0] } }} ] )

1 个答案:

答案 0 :(得分:0)

您可以使用mongoose与常规mongoDB聚合非常相似:

MessageODM().aggregate([
    {   $match: { 'receiver.email': user.email} },
    {   $sort: {dateCreated: -1} },
    {   $group: { 
           _id: { 
             sender: '$sender', 
             receiver: '$receiver' 
           },
           children: {$push: '$$ROOT'}  
    },
    { $replaceRoot: { newRoot: { $arrayElemAt: ['$children', 0] } }},
])