Mongodb field splicing $concat (aggregation)

Time:2019-12-2

$concat

Concatenate string operation, return the concatenated string. The syntax format is as follows:

{ $concat: [ <expression1>, <expression2>, ... ] }

Parameters can be any valid expression as long as they resolve to a string. For more information about expressions, see expressions.

Example

Prepare the following test data:

db.inventory.drop();
var rows = 
[
    { "_id" : 1, "item" : "ABC1", quarter: "13Q1", "description" : "product 1" },
    { "_id" : 2, "item" : "ABC2", quarter: "13Q4", "description" : "product 2" },
    { "_id" : 3, "item" : "XYZ1", quarter: "14Q2", "description" : null },
    { "_id" : 4, "item" : "CCCC", quarter: "4000"}
];
db.inventory.insert(rows);

Use $connect to connect the item and description fields, separated by “-“:

db.inventory.aggregate(
   [
      { $project: { itemDescription: { $concat: [ "$item", " - ", "$description" ] } } }
   ]
)

The operation results are as follows:

{ "_id" : 1, "itemDescription" : "ABC1 - product 1"},
{ "_id" : 2, "itemDescription" : "ABC2 - product 2"},
{ "_id" : 3, "itemDescription" : null},
{ "_id" : 4, "itemDescription" : null}

If there is abnormal data in the database that cannot be parsed into a string, such as the following data:

{ "_id" : 5, "item" : "CCCC", quarter: "4000", "description" : 4}

An error will be thrown during query. The error information is as follows:

{
    "message" : "$concat only supports strings, not double",
    "ok" : 0,
    "code" : 16702,
    "codeName" : "Location16702",
    "name" : "MongoError"
}

summary

When $concat is used for string splicing, if the parameter resolves to a null value or references a missing field, then $concat returns null.

From personal blog: learning Park
Original address: https://xuexiyuan.cn/article/detail/222.html

Recommended Today

What is blockchain? A story tells you how bitcoin works

A story tells you how bitcoin worksRecommend:Artificial intelligence: the age of artificial intelligence in the romantic capital of FranceFlowers are not flowers, things are not things, AI is not things in the pool (chapter of artificial intelligence)To our youth, a salute Pictures may be lost. It is recommended to read the original I spent the […]