0

I have a collection let's say called Persons which has the following information.

{
   name: "John Doe",
   gender: "m",
   phone: [ 123, 564, 123 ]
},
{
   name: "Elsa",
   gender: "f",
   phone: [ 456, 6789, 123 ]
},
{
   name: "Smith",
   gender: "m",
   phone: [ 55, 3244, 55]
}

What I want is to run an updateMany method query which goes through each one these objects and where ever in the array there are phone number duplication, it should remove those duplication.

As in if the phone was previously [ 123, 548, 123] I want it to be [ 123, 55 ]. I did some research on Stack overflow the implementations I found were people using aggregations or a forEach loop. Is there a better way to do it. Any help or directions would be highly appreciated.

I don't want an implementation with an aggregation or using a for loop.

So object in "John Doe" and "Elsa" can have the repeated phone number 123 But John Doe shouldn't have 123 repeated twice.

I have a collection with more then 1000 objects. Isn't there a way I could remove duplication from all objects.

Thank you.

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
  • You cannot do it with a single statement. The best you can do is ensure "new" items are considered "unique", i.e `db.collection.updateMany({},{ "$addToSet": { "phone": { "$each": [123] } } })` which would not add `123` where there already was an element. If you want to make "existing unique" you either loop the existing collection and update, or write a new collection with `aggregate()` and `$out`. Any of the ["set operators"](https://docs.mongodb.com/manual/reference/operator/aggregation-set/) of aggregation could be used to return "unique" items only. – Neil Lunn Nov 10 '17 at 03:39
  • *"I don't want an implementation with an aggregation or using a for loop."* Then you're out of luck because it's the **only** way to do it. Just learn and move on please. – Neil Lunn Nov 10 '17 at 03:42
  • But what I want is that every array would just have unique values inside it. Different object can have the same value repeated in there phone fields. But every object must have a unique phone no. set. Does this make sense? – Adeel Imran Nov 10 '17 at 03:43
  • 1
    Does not make a difference. You have been pointed at **the only way to do it**. If there was another way, I'd be writing a sprawling explanation right now of exactly how it is done differently so it can be shared and used by others. But I'm not doing that now because it simply does not exist. If you don't know how to efficiently loop or aggregate already, then read the material. If you already know how to do it, then get to doing it. Nobody can tell you any different way. – Neil Lunn Nov 10 '17 at 03:46
  • Oh okay thank you sir. I thought maybe I wasn't asking my question correctly. I'll do some more digging. Thank you for pointing me in the right direction. – Adeel Imran Nov 10 '17 at 03:47

0 Answers0