I have a MongoDB collection with the following documents
> db.mycol.find()
{ "_id" : ObjectId("5ec6506171ae442136aa97d2"), "uname" : "mail1", "port" : 1000, "abc" : "test1" }
{ "_id" : ObjectId("5ec659e6c0b1cc11370d8378"), "uname" : "mail2", "port" : 1001, "abc" : "test2" }
In the below code I am trying to fetch an array of document field port by making use of distinct in NodeJS.
var nextPort=0;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("mycol").distinct('port', function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The above code gives an output [ 1000, 1001 ]
Now, I have a variable called nextPort I want it to have the next value of already existing ports (should be unique and unused) i.e. if the last element of the array is 1001 then nextPort=1002.
How do I assign the next value (unique) from the array elements to my variable. Also is there a way to have all unique values in the document field port like we have primary key in MySQL