简体   繁体   English

如何使用MongoDB C#Driver 2.0创建流畅的聚合

[英]How to create a fluent Aggregation using MongoDB C# Driver 2.0

I'm quite new to MongoDB and I'm using it in a Web Api to serve a mobile application. 我是MongoDB的新手,我在Web Api中使用它来为移动应用程序提供服务。

Now, I need to run an aggregation and since I'm using C#, I would like to do it fluently by using the Aggregate command on a collection which returns me an IAggregateFluent . 现在,我需要运行一个聚合,因为我正在使用C#,我想通过在一个集合上使用Aggregate命令来流利地执行它,该集合返回一个IAggregateFluent

However, I'm stuck and the information which I found here on SO doesn't help me, so therefore a new question. 但是,我被困住了,我在SO上找到的信息对我没有帮助,因此是一个新问题。

I've built a small collection that holds smartphones with some basic properties, and a single item in the smartphone collection does look like: 我已经建立了一个小型集合,其中包含具有一些基本属性的智能手机,智能手机集合中的单个项目看起来像:

{
    "name" : "LG Nexus 5",
    "description" : "A Nexus 5 device, created by Google.",
    "typenr" : "LG-NEX-5/WHITE",
    "props" : [ 
        {
            "type" : "os",
            "value" : "Android"
        }, 
        {
            "type" : "storage",
            "value" : "8"
        }, 
        {
            "type" : "storage",
            "value" : "16"
        }, 
        {
            "type" : "storage",
            "value" : "32"
        }, 
        {
            "type" : "storage",
            "value" : "64"
        }
    ]
}

Now, I've created an aggregation in the shell which looks like the following: 现在,我在shell中创建了一个聚合,如下所示:

// Get all the amount of filters that are defined.
db.smartphones.aggregate([
    // Unwind the "props".
    { "$unwind" : "$props" },

    // Grouping phase.
    // Group by unique properties, add a count for the amount of articles, and add articles to an element named "articles".
    // We use the function "$addToSet" here to ensure that only unique articles are being added.
    { 
        "$group" : { 
            "_id" : "$props", 
            count : { "$sum" : 1 }, 
            articles: { 
                "$addToSet": { 
                    name: "$name", 
                    description: "$description", 
                    typenr: "$typenr" 
                } x =>
            } 
        } 
    },

    // Sort the results based on the "_id" field.
    { "$sort" : { "_id" : 1 } }
]);

And now I need to translate this to C#. 现在我需要将其转换为C#。

First, I do create the following (plain C# code, it just returns an IMongoCollection<Article> ). 首先,我创建了以下(纯C#代码,它只返回一个IMongoCollection<Article> )。

var collection = context.ArticleRepository;

Here's the model which the collection does return: 这是集合确实返回的模型:

public class Article
{
    #region Properties

    /// <summary>
    ///     Unique identifier for the article.
    /// </summary>
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    /// <summary>
    ///     Name of the article.
    /// </summary>
    [BsonElement("name")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Name { get; set; }

    /// <summary>
    ///     Name of the element but in lowercase.
    /// </summary>
    /// <remarks>
    ///     We'll create this field to enable text-search on this field without respecting capital letters.
    /// </remarks>
    [BsonElement("namelc")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString LowercaseName { get; set; }

    /// <summary>
    ///     Specification of the article.
    /// </summary>
    [BsonElement("specification")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Specificiation { get; set; }

    /// <summary>
    ///     Brand of the article.
    /// </summary>
    [BsonElement("brand")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Brand { get; set; }

    /// <summary>
    ///     Supplier of the article.
    /// </summary>
    [BsonElement("supplier")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public Supplier Supplier { get; set; }

    /// <summary>
    ///     Number of the article.
    /// </summary>
    [BsonElement("nr")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString ArticleNumber { get; set; }

    /// <summary>
    ///     Gtin number of the article.
    /// </summary>
    [BsonElement("gtin")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public string ArticleGtin { get; set; }

    /// <summary>
    ///     type number of the article.
    /// </summary>
    [BsonElement("typeNr")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public string TypeNumber { get; set; }

    /// <summary>
    ///     Properties of the article.
    /// </summary>
    /// <remarks>
    ///     This field can be used to ensure that we can filter on the articles.
    ///     By default, this is an empty list, this avoids initialization logic.
    /// </remarks>
    [BsonElement("props")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public List<ArticleProperty> Properties { get; set; } = new List<ArticleProperty>();

    #endregion
}

/// <summary>
///     Class representing a single supplier in the database.
/// </summary>
/// <remarks>
///     This class is not used as a "root" document inside our database.
///     Instead, it's being embedded into our "Articles" document.
/// </remarks>
public class Supplier
{
    #region Properties

    /// <summary>
    ///     Name of the supplier.
    /// </summary>
    [BsonElement("supplier")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Name { get; set; }

    /// <summary>
    ///     Gln of the supplier.
    /// </summary>
    [BsonElement("gln")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Gln { get; set; }

    #endregion
}

/// <summary>
///     Class representing a single property for an article in the database.
/// </summary>
/// <remarks>
///     This class is not used as a "root" document inside our database.
///     Instead, it's being embedded into our "Articles" document.
/// </remarks>
public class ArticleProperty
{
    #region Properties

    /// <summary>
    ///     Type of the property.
    /// </summary>
    [BsonElement("type")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Type { get; set; }

    /// <summary>
    ///     Value of the property.
    /// </summary>
    [BsonElement("value")]
    [BsonIgnoreIfNull]
    [BsonIgnoreIfDefault]
    public BsonString Value { get; set; }

    #endregion
}

Now, I need to aggregate on this collection, and I'm strugling already with the basics: 现在,我需要在这个集合上进行聚合,而且我已经对基础知识进行了深入研究:

// Build the aggregation using the fluent api.
var aggregation = collection.Aggregate()
    .Unwind(x => x.Properties)
    .Group(x => new { x.Properties );

Right now, I only try to group on properties, like in the aggregation but this results in the following error: 现在,我只尝试对属性进行分组,就像在聚合中一样,但这会导致以下错误:

CS0411 The type arguments for method 'IAggregateFluent<BsonDocument>.Group<TNewResult>(ProjectionDefinition<BsonDocument, TNewResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

But even when that's working, I also need the extra properties as count and addToSet . 但即使它正在工作,我还需要额外的属性作为countaddToSet Can someone help me with this one. 有人可以帮助我这个。 I'm already searching for 2 days on this and it's driving me crazy. 我已经在这上面搜索了2天,这让我发疯了。

Edit 编辑

I've found that a group followed by an unwind does work in C#, but why doesn't it work with the unwind first? 我发现一个后续放松的小组确实在C#中工作,但为什么它不能先解开呢? I really need the unwind to happen first. 我真的需要先放松一下。

Edit 2 I've managed to get a small portion working, inclusive the group command. 编辑2我设法让一小部分工作,包括group命令。 See the code below: 请参阅以下代码:

var aggregation = collection.Aggregate()
    .Unwind<Smartphone, UnwindedSmartphone>(x => x.Properties)
    .Group(key => key.Property, g => new
    {
        Id = g.Key,
        Count = g.Count()
    });

However, I need some more information on how to push the Articles property from the aggregation command. 但是,我需要更多关于如何从聚合命令中推送Articles属性的信息。

I've found the solution to the problem. 我找到了问题的解决方案。 The following C# code should be used: 应使用以下C#代码:

var aggregation = collection.Aggregate()
    .Unwind<Smartphone, UnwindedSmartphone>(x => x.Properties)
    .Group(key => key.Property, g => new
    {
        Id = g.Key,
        Count = g.Count(),
        Articles = g.Select(x => new
        {
            Name = x.Name
        }).Distinct()
    })
    .SortBy(x => x.Id);

This gives me the following aggregation: 这给了我以下聚合:

db.smartphones.aggregate([{ "$unwind" : "$props" }, { "$group" : { "_id" :     "$props", "Count" : { "$sum" : 1 }, "Articles" : { "$addToSet" : { "Name" :     "$name" } } } }, { "$sort" : { "_id" : 1 } }])

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

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