去重 - MongoDB如何去除組合重複項
高洛峰
高洛峰 2017-04-27 09:02:29
0
3
1109
雷雷
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(3)
某草草

雷雷

習慣沉默

雷雷

洪涛
> db.test.find()
{ "_id" : ObjectId("55de6075024f45b4947d4cc3"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 12 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc4"), "name" : "zhangsan", "sex" : "MALE", "age" : 16 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc5"), "name" : "lisi", "sex" : "FEMALE", "age" : 20 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc6"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 25 }
{ "_id" : ObjectId("55de6076024f45b4947d4cc7"), "name" : "lisi", "sex" : "FEMALE", "age" : 36 }
{ "_id" : ObjectId("55de6077024f45b4947d4cc8"), "name" : "zhangsan", "sex" : "FEMALE", "age" : 28 }
> db.test.aggregate([
...     { $group: { _id: { name: "$name", sex: "$sex" } } }
... ])
{ "_id" : { "name" : "lisi", "sex" : "FEMALE" } }
{ "_id" : { "name" : "zhangsan", "sex" : "MALE" } }
{ "_id" : { "name" : "zhangsan", "sex" : "FEMALE" } }
> db.test.distinct("name");
[ "zhangsan", "lisi" ]
> db.test.distinct("name","sex");
[ "zhangsan", "lisi" ]
> db.test.distinct("name","sex","age");
[ "zhangsan", "lisi" ]

樓上的方法是正確的,mongoDB確實不支援組合去重,mongo官網提供的範例也只是對單一欄位去重。

官網範例: http://docs.mongodb.org/manual/core/single-purpose-aggregation/

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板