0

I've got a query and it works perfectly in shell

db.getCollection('chatmessages').aggregate(
[
    { 
        $match : { 
            ChatId: { $in : [ObjectId("59edf7d34330cf25d6acd3fb")] }
        },
    },
    { 
        $group : { 
            _id : { ChatId : "$ChatId" },
            LastMessage : { $first : "$$CURRENT"}
        }
    }
])

But when I'm trying to make it work in c# like this:

        var list = await _mongoCollection.Aggregate()
            .Match(mes => chatIdsObject.Contains(mes.ChatId))
            .SortBy(mes => mes.ChatId)
            .ThenByDescending(mes => mes.CreateDateTime)
            .Group(
                key => key.ChatId,
                group => new
                {
                    ChatId = group.Key,
                    LastMessage = group.Select(x => x).First()
                })
            .ToListAsync();

I get an error:

$project or $group does not support {document}.

Is there a way to make $first in cooperation with $$CURRENT work in C#?

  • That's not supported yet, also see this SO question: https://stackoverflow.com/questions/35386845/mongodb-c-sharp-get-latest-document-from-group – dnickless Oct 27 '17 at 14:52

1 Answers1

0

An alternative would be to inject the json in your pipeline as:

var list = await _mongoCollection.Aggregate()
    .Match(mes => chatIdsObject.Contains(mes.ChatId))
    .SortBy(mes => mes.ChatId)
    .ThenByDescending(mes => mes.CreateDateTime)
    .Group(new JsonProjectionDefinition<ChatMessages>(@"{ 
        '_id' : { 'ChatId' : '$ChatId' },
        'LastMessage' : { '$first' : '$$CURRENT' }
    }"))
    .ToListAsync();
chridam
  • 100,957
  • 23
  • 236
  • 235