Group query upon nested object in MongoDB?
为此,在 MongoDB 中,使用点符号以及 $group 。让我们使用文档创建一个集合 -
> db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "Chris", ... "Age":32, ... "Project":"Online Library Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b86c954c74be91e69b") } > > db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "David", ... "Age":34, ... "Project":"Online Hospital Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b86c954c74be91e69c") } > > db.demo617.insertOne( ... { ... ... "clientDetails": { ... "Name": "David", ... "Age":34, ... "Project":"Online Library Management System" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e99d2b96c954c74be91e69d") }
在集合中显示所有文档,使用 find() 方法 -
> db.demo617.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e99d2b86c954c74be91e69b"), "clientDetails" : { "Name" : "Chris", "Age" : 32, "Project" : "Online Library Management System" } } { "_id" : ObjectId("5e99d2b86c954c74be91e69c"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Hospital Management System" } } { "_id" : ObjectId("5e99d2b96c954c74be91e69d"), "clientDetails" : { "Name" : "David", "Age" : 34, "Project" : "Online Library Management System" } }
在 MongoDB 中,对嵌套对象进行组查询 -
> db.demo617.aggregate({ $group : {_id : "$clientDetails.Project", All : { $sum : 1 }} });
这将产生以下输出 -
{ "_id" : "Online Hosiptal Management System", "All" : 1 } { "_id" : "Online Library Management System", "All" : 2 }
广告