确认数组中的所有对象某一字段的取值是否是唯一的

MongoDB数据如下

> db.foo.find()
{ "_id" : ObjectId("5ae84b29fca5249951cadc26"), "id" : 1, "datas" : [ { "content_type" : 0 } ] }
{ "_id" : ObjectId("5ae84b29fca5249951cadc27"), "id" : 2, "datas" : [ { "content_type" : 0 }, { "content_type" : 0 } ] }
{ "_id" : ObjectId("5ae84b29fca5249951cadc28"), "id" : 3, "datas" : [ { "content_type" : 2 }, { "content_type" : 2 } ] }
{ "_id" : ObjectId("5ae84b29fca5249951cadc29"), "id" : 4, "datas" : [ { "content_type" : 0 }, { "content_type" : 2 } ] }
{ "_id" : ObjectId("5ae84c01fca5249951cadc2a"), "id" : 5, "datas" : [ { "content_type" : 2 } ] }

需求
确认datas数组中每个对象的content_type取值是一样的 即都是0或者都是2

确认语句

> db.foo.aggregate(
... {$unwind:"$datas"},
... {$group:{"_id":{id:"$id",content_type:"$datas.content_type"}}},
... {$group:{"_id":"$_id.id",count:{$sum:1}}},
... {$match:{count:{$gt:1}}}
... )
{ "_id" : 4, "count" : 2 }

表示datas数组中存在content_type取值不唯一的情况

不知还有没其他方案 可以确认数组下所有对象的某一字段的取值是否都一致 即表示数组中的对象都是同属一类的

阅读 1.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进