MongoDB $concat OperatorWhat is the $concat operator in MongoDB?MongoDB provides a variety of string expression operators that are used in the aggregation pipeline stages. The $concat operator is one of those operators. The $concat operator is used to concatenate two or more strings into a single string. Syntax of the $concat operator:The argument passed in this operator can be any valid expression until it resolves to the string.
Examples:Suppose we have a collection of the students with the following documents. Example 1: Using $concat operator In this example, we're going to concatenate the name field with surname field using the $concat operator. Output: { "_id" : 1, "name" : "SteveSmith", "department" : "B-tech", "fees" : 80000 } { "_id" : 2, "name" : "SandyBeach", "department" : "BCA", "fees" : 55000 } { "_id" : 3, "name" : "JohnCena", "department" : "MCA", "fees" : 85000 } { "_id" : 4, "name" : "WickJohn", "department" : "B.com", "fees" : 60000 } { "_id" : 5, "name" : "DavidSilva", "department" : "null", "fees" : 80000 } Suppose we add the following documents to our collection: { "_id" : 6, "name" : "null", "surname" : "Thomas", "department" : "M.com", "fees" : 60000 } { "_id" : 7, "name" : "David", "surname" : "null", "department" : "BCA", "fees" : 60000 } Example 2: Null Values In this example, we're going to concatenate the name field with surname field using the $concat operator. Output: { "_id" : 6, "name" : null, "department" : "M.com", "fees" : 60000 } { "_id" : 7, "name" : null, "department" : "BCA", "fees" : 60000 } Example 3: More than two string In this example, we're going to concatenate the name field with surname using the $concat operator. Output: { "_id" : 1, "name" : "Steve Smith", "department" : "B-tech", "fees" : 80000 } { "_id" : 2, "name" : "Sandy Beach", "department" : "BCA", "fees" : 55000 } { "_id" : 3, "name" : "John Cena", "department" : "MCA", "fees" : 85000 } Another example: Output: { "_id" : 1, "Student" : "Steve Smith, B-tech", "fees" : 80000 } { "_id" : 2, "Student" : "Sandy Beach, BCA", "fees" : 55000 } { "_id" : 3, "Student" : "John Cena, MCA", "fees" : 85000 } Next TopicMongoDB $nin Operator |