【问题标题】:C# Mongodb - Get document and matching array elementsC# Mongodb - 获取文档和匹配的数组元素
【发布时间】:2018-10-23 09:24:27
【问题描述】:

一直在尝试查询 BsonArray 中包含评级和 cmets 的文档。 我试图得到的结果是根文档和数组中匹配用户的匹配元素。

    public class Blends
{
    public BsonObjectId _id { get; set;}
    public BsonObjectId GinID { get; set;}
    public BsonObjectId TonicID { get; set;}
    public BsonObjectId GarnishID { get; set;}
    public string GinName { get; set;}
    public string TonicName { get; set;}
    public string GarnishName { get; set;}
    public double Rating { get; set;}
    public double RatingSum { get; set;}
    public double RatingCount { get; set;}
    public List<Reviews> Review { get; set;}
}

    public class Reviews
{
    public int Commentnumber { get; set; }
    public string User { get; set; }
    public int Rating { get; set; }
    public string Comment { get; set; }
    public int Helpfull { get; set; }
}

我测试了很多方法,在“Review”中只返回1个匹配

var client = new MongoClient(connectionString);
IMongoDatabase db = client.GetDatabase("GinAndTonic");
var collection = db.GetCollection<Blends>("Blends");
var builder = Builders<Blends>.Filter;
var filter = builder.Eq("Review.User", username);
var fieldsbuilder = Builders<Blends>.Projection;
var fields = fieldsbuilder.Include("Review.$");

var result = await collection.Find(filter).Project<Blends>(fields).ToListAsync();

希望有人可以帮助解决这个问题。

【问题讨论】:

    标签: c# mongodb nosql


    【解决方案1】:

    这应该可以帮助您:

    var result = await collection
                    .Aggregate().Match(b => b.Review.Any(r => r.User == username))
                    .Project(b => new { Review = b.Review.Where(r => r.User == username) })
                           .ToListAsync();
    

    【讨论】:

    • 似乎仍然给我相同的结果,只有第一个匹配结果的数组对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2011-12-19
    • 2015-11-04
    • 2016-09-01
    • 1970-01-01
    相关资源
    最近更新 更多