1.$project
0. Basic Usage
Run the following command to filter return fields
// Add field, delete field
{
"$project" : {
"userId" : "$_id"."$_id" : 0}}Copy the code
1. Mathematical expressions
Function: new field, return the basic operation (add, subtract, multiply, divide, mod) results;
// Multiple values can be added
{
"$project" : {
"total" : {
"$add" : ["$fieldname1"."$fieldname2"."..."]}}}Copy the code
// The first value minus the second value
{
"$project" : {
"total" : {
"$subtract" : ["$fieldname1"."$fieldname2"]}}}Copy the code
// Multiple values can be multiplied
{
"$project" : {
"total" : {
"$multiply" : ["$fieldname1"."$fieldname2"."..."]}}}Copy the code
// The first value divided by the second value
{
"$project" : {
"total" : {
"$divide" : ["$fieldname1"."$fieldname2"]}}}Copy the code
// The first value is mod by the second value
{
"$project" : {
"total" : {
"$mod" : ["$fieldname1"."$fieldname2"]}}}Copy the code
2. String expressions
Function: string operation, clipping, splicing, uppercase, lowercase;
// Clipping param1, starting with param2, param3 bytes (bytes not characters, note in multi-byte encoding);
{
"$project" : {
"total" : {
"$substr" : ["$fieldname".0.1]}}}Copy the code
// Concatenate all params in order (constants, results, other fields)
{
"$project" : {
"total" : {
"$concat" : [
"abc",
{"$substr" : ["$fieldname".0.1]},
"$fieldname"]}}}Copy the code
// Convert the field to lowercase
{
"$project" : {
"total" : {
"$toLower" : "$fieldname"}}}Copy the code
// Uppercase the field
{
"$project" : {
"total" : {
"$toUpper" : "$fieldname"}}}Copy the code
3. Logical expressions
Function: Some logical expressions can be used to control statements;
1. Compare expressions
$fieldName === 0 total = 0;
$fieldName > 0 total = 1;
$fieldName < 0 total = -1;
{
"$project" : {
"total" : {
"$cmp" : ["$fieldname".100]}}}Copy the code
// This book is case sensitive. The latest official mongodb documentation is case insensitive
$fieldName === 0 total = 0;
$fieldName > 0 total = 1;
$fieldName < 0 total = -1;
{
"$project" : {
"total" : {
"$strcasecmp" : ["$fieldname"."asd"]}}}Copy the code
//"$eq" "$ne" "$gt" "$gte" "$lt" "$lte"
// Param1 is compared with param2 and returns true or false
{
"$project" : {
"total" : {
"$lt" : ["$fieldname".10]}}}Copy the code
2. Boolean expressions
//"$and" expr1 expr2... All expressions are true and return true, otherwise false
//"$or" expr1 expr2... Any expression true returns true, otherwise false
//"$not" expr1
{
"$project" : {
"total" : {
"$and": [{"$gt": [ "$qty".100] {},"$lt": [ "$qty".250]}]}}Copy the code
3. Control statements
//"$cond" param1 returns param2 if true, param3 if not. (similar to the JS ternary operator)
{
"$project" : {
"total" : {
"$cond": [{"$gte": [ "$qty".250]},30.20]}}}Copy the code
//"$ifNull" param1 ifNull returns param2, otherwise returns param1
{
"$project" : {
"total" : {
"$ifNull": [ "$description"."Unspecified"]}}}Copy the code
4. More
The official documentation