欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mongodb aggregate示例

程序员文章站 2022-07-07 15:36:52
...

 在

db.award.aggregate(

	// Pipeline
	[
		// Stage 1
		{
			$lookup: { "from" : "merchant" , "localField" : "merchantId" , "foreignField" : "_id" , "as" : "merchant"}
		},

		// Stage 2
		{
			$unwind: "$merchant"
		},

		// Stage 3
		{
			$match: {
			"merchant.name":{$regex:".*麦当劳.*"}
			}
		},

		// Stage 4
		{
			$project: {
			   "merchantId":1,"merchant.name":1,
			   "collectWordColumn":{
			     $cond:{
			         if:{
			             $eq:["$type","1"]
			         },then:1,else:0
			     }
			   },
			   "scratchColumn":{
			     $cond:{
			         if:{
			             $in:["$type",["2","3"]]
			         },then:1,else:0
			     }
			   },
			   "jigsawColumn":{
			     $cond:{
			         if:{
			             $eq:["$type","5"]
			         },then:1,else:0
			     }
			   },
			}
		},

		// Stage 5
		{
			$group: {
			"_id":"$merchantId",
			"collectWordCount" : { "$sum" : "$collectWordColumn"},
			"scratchCount" : { "$sum" : "$scratchColumn"},
			"jigsawCount" : { "$sum" : "$jigsawColumn"},
			"awardCount" : { "$sum" : 1},
			}
		},

		// Stage 6
		{
			$limit: 20
		},

		// Stage 7
		{
			$skip: 0
		},

		// Stage 8
		{
			$sort: {
			"_id":-1
			}
		},
	],

	// Options
	{
		cursor: {
			batchSize: 50
		}
	}

	// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/

);