简体   繁体   English

C#在MongoDB文档上使用投影

[英]C# using projection on MongoDB document

I'm trying to get only a few values from an document that has been unwinded. 我正试图从已经解散的文档中获取一些值。

Right now I get all of this, but I only want the values from "reviews" 现在,我得到了所有这些,但是我只想要“评论”中的值

{ "_id" : ObjectId("57ced083857eda00e03b5a5e"), "name" : "Rest2", "reviews" : { "_id" : ObjectId("57ced083857eda00e03b5a60"), "rating" : 4, "date" : ISODate("2016-09-05T22:00:00Z") } }

My current aggregate function looks like this: 我当前的聚合函数如下所示:

var coll = Database.GetCollection<Restaurant>("restaurants")
            .Aggregate()
            .Match(new BsonDocument { { "name", nameRest } })
            .Unwind(x => x.reviews);
        var result = await coll.ToListAsync();

How do you project only those values? 您如何仅投影这些值? Help would be greatly appreciated! 帮助将不胜感激!

Based on your example, you can use project like below: 根据您的示例,您可以使用如下项目:

var coll = Database.GetCollection<Restaurant>("restaurants")
        .Aggregate()
        .Match(new BsonDocument { { "name", nameRest } })
        .Unwind(x => x.reviews)
        .Project(new BsonDocument { {"rating", "$reviews.rating"} })

var result = await coll.ToListAsync();

The result of the above example would output only reviews.rating and _id field. 上面示例的结果将仅输出reviews.rating_id字段。 See aggregation operator $project for more information. 有关更多信息,请参见聚合运算符$ project

The snippet above was tested using MongoDB C# Driver v2.2 , MongoDB v3.2 and .Net v4.5 上面的代码段已使用MongoDB C#驱动程序v2.2 ,MongoDB v3.2和.Net v4.5进行了测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM