使用mongodb C#驱动程序选择一个BsonDocument,其数组只包含最后N个元素

时间:2016-09-27 11:04:53

标签: c# mongodb bson

我在MongoDB中有一个像这样的BsonDocuments的集合

messages: [
{
time: "0001-01-01T00:00:00Z",
room: "ROOM2",
receiver: "xxxxxxxxx@xxx.xxx",
receiverName: "xxxxxxxxx",
sender: "xxxxxxxxx@xxx.xxx",
senderName: "xxxxxxxxx",
message_text: "jl,hrdls"
},
{
time: "0001-01-01T00:00:00Z",
room: "ROOM2",
receiver: "xxxxxxxxx@xxx.xxx",
receiverName: "xxxxxxxxx",
sender: "xxxxxxxxx@xxx.xxx",
senderName: "xxxxxxxxx",
message_text: "hello world"
},
{
time: "0001-01-01T00:00:00Z",
room: "ROOM2",
receiver: "xxxxxxxxx@xxx.xxx",
receiverName: "XXXXXXXXX",
sender: "XXXXXXXX@xxx.xxx",
senderName: "XXXXX",
message_text: "hello world"
}
],
_id: 4,
email1: "xxxx@XXX.xxx",
email2: "xxxxxx@xxx.xxx"

现在使用MongoDB的C#驱动程序我想选择这些文档,使 'messages' 数组只包含最后两个元素...我找不到任何解决方案。 ..有人可以建议一个方法吗?

2 个答案:

答案 0 :(得分:0)

如果您对解决方法感到满意:

从Mongo集合中选择正确的文档到List - 这里命名为result

    var filter = Builders<Entity>.Filter.Eq("email1", "email@one.net");
    List<Entity> result = await msgs.Find(filter).ToListAsync();

您可以遍历结果并仅保留前两个消息条目:

foreach (Entity item in result)
            {
                item.messages = item.messages.OrderByDescending(p => p.time).Take(2).ToList();
            }

其中Entity是表示模型的类型。类似的东西:

class Entity
    {
        public BsonObjectId _id { get; set; }
        public string email1 { get; set; }
        public string email2 { get; set; }
        public List<Message> messages { get; set; }

        public Entity()
        {
            messages = new List<Message>();
        }
    }

    class Message
    {
        public DateTime time { get; set; }
        public string room { get; set; }
        //...
        public string message_text { get; set; }
    }

答案 1 :(得分:0)

你需要做这样的投影,只包括你想要的字段:

var query = collection.Find(filter).   // your filter
               Project<Document>(
               Builders<Document>.Projection
                                 .Include("messages.senderName")
                                 .Include("messages.message_text")
                                 .Include("email1")
                                 .Include("email2")
);

为此,我认为您需要使用[BsonElement(&#34; messages&#34;)]属性声明您的实体。

如果有效,请告诉我。