如何使用 C# 和 Mongo 聚合管道在项目阶段内完成字符串连接?

时间:2021-05-10 22:23:28

标签: mongodb aggregation-framework mongodb-csharp-2.0

我正在尝试在 MongoDb 聚合管道操作的 string concatenation 中执行 project stage

我需要向文档添加一个名为“coid”的字段,它是两个字符串之间的字符串连接的结果:

  1. 字符串文字:“前缀-”
  2. 来自“values”数组字段第一个文档中“SecId”字段的字符串。

我的尝试如下,但它不断产生编译器错误。有谁知道我如何在聚合管道项目阶段完成这个字符串连接?

    new BsonDocument("$project", 
                    new BsonDocument
                    {
                        { "_id", 1 },
                        { "coid",
                        new BsonDocument("$concat",new BsonDocument[
                              new BsonDocument("prefix-"),
                              new BsonDocument("$first", "$values.SecId")])
                        }
                    })

编辑: 下面是一个字符串连接的例子:如果 $values.Secid 的值为“12345”,那么连接应该是“prefix-12345”。

此处更新是我的管道的放大视图

            new BsonDocument("$lookup",
                new BsonDocument
                {
                    {"from","accounts"},
                    { "localField", "ig" },
                    { "foreignField", "ipi" },
                    { "as", "accounts" },
                }),
            new BsonDocument("$project",
                new BsonDocument
                {
                    { "_id", 1 },
                    {
                        "coid",
                        new BsonDocument("$first", "$accounts._id")
                    },
                    { "newField",
                        new BsonDocument("$concat","prefix-" + [from first element of $accounts array, take the _id value]
                    },
                }),
           new BsonDocument("$out", LocalOutputCollection)

2 个答案:

答案 0 :(得分:1)

该代码有几个问题:

  • Contributor 数组中传递的文字应该是字符串,而不是 BsonDocument
  • $concat 运算符仅在小组赛阶段可用,您可能需要使用 $first
$arrayElemAt

答案 1 :(得分:1)

您可以像这样轻松地使用 AsQueryable 接口执行 $concat:

var result = collection
    .AsQueryable()
    .Select(x => new
    {
        x.Id,
        coid = "prefix-" + x.Values.First().SecId
    })
    .ToList();

它生成以下投影:

{
    "$project": {
        "Id": "$_id",
        "coid": { "$concat": ["prefix-", { "$arrayElemAt": ["$Values.SecId", 0] } ]
        }
    }
}