DEV Community

Henrique Marques Fernandes
Henrique Marques Fernandes

Posted on • Originally published at marquesfernandes.com on

Como Verificar Itens Duplicados no Array no MongoDB

Se você tem uma collection grande e precisa descobrir se existem items com valores duplicados dentro de um array. Esse problema algum dia provavelmente irá acontecer com você, mas não se preocupe! Para verificar se há duplicatas em um array, usaremos o .aggregate() no MongoDB.

Vamos criar uma coleção com documentos de exemplo, primeiro inserimos um registro de teste:

db.demo.insertOne({"assunto":["MySQL","MongoDB","Node", "MySQL"]});
Enter fullscreen mode Exit fullscreen mode

Depois vamos inserir mais um registro com um item duplicado dentro do nosso array de assunto:

db.demo.insertOne({"assunto":["Java","C+","Node", "C+"]});
Enter fullscreen mode Exit fullscreen mode

E agora apenas para teste, vamos inserir um registro sem nenhum item duplicado:

db.demo.insertOne({"assunto":["JavaScript","C#","Python"]});
Enter fullscreen mode Exit fullscreen mode

Agora exiba todos os documentos da nossa coleção com a ajuda do método .find()

db.demo.find();
Enter fullscreen mode Exit fullscreen mode

Isso produzirá o seguinte resultado:

/\* 1 \*/ { "\_id" : ObjectId("5f89f5da526ef077555fe4aa"), "assunto" : ["MySQL", "MongoDB", "Node"] } /\* 2 \*/ { "\_id" : ObjectId("5f89f718526ef077555fe4ab"), "assunto" : ["Java", "C+", "Node"] } /\* 3 \*/ { "\_id" : ObjectId("5f89f71f526ef077555fe4ac"), "assunto" : ["JavaScript", "C#", "Python"] }
Enter fullscreen mode Exit fullscreen mode

Usaremos o método .aggregate para consultar e verificar se há duplicatas em uma matriz nos documentos da nossa coleção:

db.demo.aggregate([{"$project": {"assunto":1}}, {"$unwind":"$assunto"}, {"$group": {"\_id":{"\_id":"$\_id", "Name":"$assunto"}, "count":{"$sum":1}}}, {"$match": {"count":{"$gt":1}}}, {"$group": {"\_id": "$\_id.\_id", "assunto":{"$addToSet":"$\_id.Name"}}}])
Enter fullscreen mode Exit fullscreen mode

Você deve esperar o seguinte resultado:

/\* 1 \*/ { "\_id" : ObjectId("5f89ff1f526ef077555fe4b0"), "assunto" : ["MySQL"] } /\* 2 \*/ { "\_id" : ObjectId("5f89ff24526ef077555fe4b1"), "assunto" : ["C+"] }
Enter fullscreen mode Exit fullscreen mode

O post Como Verificar Itens Duplicados no Array no MongoDB apareceu primeiro em Henrique Marques Fernandes.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay