B
B
bro-dev2018-03-13 11:14:03
JavaScript
bro-dev, 2018-03-13 11:14:03

How to remove duplicate fields of array type?

How to remove duplicate fields of array type? for 1 request to the database.
there is a document

{
ar:[0,1,2,1,2,3,1,2,3,1,2,3,3,1,3,1,1,3,2,1,3,2,1,2,3,1,3,2]
}

How can I make sure that only unique values ​​remain there? So far, everything has been done through the node, that is, it receives the document, processes it and writes it, the problem is that there are more than a million of these records, of which a third are unique. and due to these, memory and percent are being eaten here and there, I would like for 1 request to make the mong inside herself, is it possible?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
riot26, 2018-03-13
@riot26

let ar = [0,1,2,1,2,3,1,2,3,1,2,3,3,1,3,1,1,3,2,1,3,2,1,2,3,1,3,2];
let result = [...new Set(ar)];
console.log(result);

M
Maxim Timofeev, 2018-03-13
@webinar

function onlyUnique(value, index, self) { 
    return self.indexOf(value) === index;
}

var a = [0,1,2,1,2,3,1,2,3,1,2,3,3,1,3,1,1,3,2,1,3,2,1,2,3,1,3,2];
var unique = a.filter( onlyUnique );

D
dmitrygavrish, 2018-03-13
@dmitrygavrish

db.collection.distinct(field, query, options):
https://docs.mongodb.com/manual/reference/method/d...
to execute this query via mongoose, you can start searching at:
https://stackoverflow .com/questions/6043847/how-do...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question