Does aggregation query with $match works in MongoDB?
可以,它在 MongoDB 中有效。让我们创建一个包含文档的集合 -
> db.demo358.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5e5692c0f8647eb59e5620cb") } > db.demo358.insertOne({"ClientId":102,"ClientName":"David","ClientAge":32}); { "acknowledged" : true, "insertedId" : ObjectId("5e5692caf8647eb59e5620cc") } > db.demo358.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e5692d2f8647eb59e5620cd") } > db.demo358.insertOne({"ClientId":104,"ClientName":"Bob","ClientAge":31}); { "acknowledged" : true, "insertedId" : ObjectId("5e5692ddf8647eb59e5620ce") } > db.demo358.insertOne({"ClientId":105,"ClientName":"Chris","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5e5692e7f8647eb59e5620cf") }
使用 find() 方法显示集合中的所有文档 -
> db.demo358.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e5692c0f8647eb59e5620cb"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 } { "_id" : ObjectId("5e5692caf8647eb59e5620cc"), "ClientId" : 102, "ClientName" : "David", "ClientAge" : 32 } { "_id" : ObjectId("5e5692d2f8647eb59e5620cd"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 } { "_id" : ObjectId("5e5692ddf8647eb59e5620ce"), "ClientId" : 104, "ClientName" : "Bob", "ClientAge" : 31 } { "_id" : ObjectId("5e5692e7f8647eb59e5620cf"), "ClientId" : 105, "ClientName" : "Chris", "ClientAge" : 36 }
以下是使用 aggregate 中的 $match 的方法 -
> db.demo358.aggregate( ... [ { $match : { "ClientName" : "David" }}, ... { "$count": "ClientName" } ... ] ... );
这将产生以下输出 -
{ "ClientName" : 2 }
广告