如何查找给定字段没有重复值的 mongo 文档 [英] How to find mongo documents with no duplicates values for a given field

查看:43
本文介绍了如何查找给定字段没有重复值的 mongo 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定这个数据集:

db.mycollection.insert([
  {a:1, b:2, c:3},
  {a:1, b:3, c:4},
  {a:0, b:1, c:3},
  {a:3, b:2, c:4}
])

我需要一种方法来列出所有没有重复值的文档,比如字段a".

I need a way to list all documents that doesnt have duplicates values for, let say, the field "a".

所以它需要返回:

[{a:0, b:1, c:3}, {a:3, b:2, c:4}]

推荐答案

您需要使用 聚合框架 以获得所需的结果.聚合管道如下所示:

You need to use the aggregation framework to get the desired result. The aggregation pipeline would look like this:

db.mycollection.aggregate([
   {
       "$group": {
           "_id": "a",
           "data": { "$first": "$$ROOT" },
           "count": { "$sum": 1 }
       }
   },
   {
       "$match": { "count": 1 }
   },
   {
       "$project": {
           "_id": 0, "a": "$data.a", "b": "$data.b", "c": "$data.c" 
       }
   }
])

这篇关于如何查找给定字段没有重复值的 mongo 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆