I'm trying to perform a string concatenation within a project stage of a MongoDb aggregation pipeline operation.
I need to add a field called "coid" to a document, which is to be the result of a string concation between 2 strings:
My attempt is below, but it keeps generating a compiler error. Does anyone know how I can accomplish this string concatenation, within the aggregation pipeline project stage?
new BsonDocument("$project",
new BsonDocument
{
{ "_id", 1 },
{ "coid",
new BsonDocument("$concat",new BsonDocument[
new BsonDocument("prefix-"),
new BsonDocument("$first", "$values.SecId")])
}
})
Edit: Here is an example of one string concatenation: If the value of $values.Secid is "12345", then the concatenation should be "prefix-12345".
Update here is an enlarged view of my pipeline
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)
There are a couple problems with that code:
$concat
array should be string, not BsonDocument $first
operator is only available in a group stage, you probably need to use $arrayElemAt
new BsonDocument("$concat",
new BsonDocument[
"prefix-",
new BsonDocument(
"$arrayElemAt",
new BsonDocument[ "$values.SecId", 0]
)
]
)
you can easily do $concat with the AsQueryable
interface like so:
var result = collection
.AsQueryable()
.Select(x => new
{
x.Id,
coid = "prefix-" + x.Values.First().SecId
})
.ToList();
it generates the following projection:
{
"$project": {
"Id": "$_id",
"coid": { "$concat": ["prefix-", { "$arrayElemAt": ["$Values.SecId", 0] } ]
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.