Today there is a new requirement, and one department needs to get data from MongoDB, requiring that one of the fields be stripped of the same content.
Although MongoDB distinct come and go, but unlike MySQL's distinct, MySQL can use distinct * to return the entire record of information, And MongoDB's distinct I just return to the data of the field of the heavy (perhaps MongoDB can also return the whole article, but I do not know).
Distinct in MySQL returns the full record:
Distinct in MongoDB to re-weight a field:
The above is not the result I want to see, so I think of a way to remove the duplicate data after the re-save the non-duplicated data into a table, the following is an example: 1, into the MONGO shell:
./mongo
2. Switch to the database where you want to go to the heavy collection:
Use admin
3. Write and execute the JS code in the MONGO shell:
var res=db.test.find (); while (Res.hasnext ()) { var res1=db.test.find (); var re=res.next (); while (Res1.hasnext ()) { var re1=res1.next (); if (re.age==re1.age) { Db.test.remove ({"Age": Re1.age}); } } Db.test.insert (re); }
For example, the first time the loop is executed because the RES has no definition and fails, the second time the res is defined, the execution succeeds. Then in the new collection, there is absolutely no data to duplicate in the field (this is just the test below, so the same set is used).
MongoDB to remove duplicate data