0

By default, mongodb adds documents to the end of collection. However, I want them to be added at the first position in the collection. The code I have is,

  MongoClient mongo = new MongoClient("localhost", 27017);
  DB db = mongo.getDB("test");
  DBCollection collection = db.getCollection("lwjsons");        
  BasicDBObject document = new BasicDBObject();
  collection.insert(dbObject);
G.Brown
  • 369
  • 3
  • 16
  • 1
    See [How does MongoDB sort records when no sort order is specified?](https://stackoverflow.com/a/11599283/2313887) which should inform that there is "no order of documents at all". If you want things to *come out in a certain order* then you pick a property ( optionally created if you must ) and **sort** on it. But there is no such thing as "record order" or "insertion order". ( with the exception of capped collections, but the answer does say that ) – Neil Lunn Mar 18 '19 at 05:46
  • so, what would be the code for this? – G.Brown Mar 18 '19 at 05:57
  • You can use `sort` when finding data. – Ashwanth Madhav Mar 18 '19 at 06:07
  • no, I am not finding anything. I just want the record to be inserted at the first position rather than last – G.Brown Mar 18 '19 at 06:35
  • you are inserting to a collection in the database. This is not like Array `push` or array `unshift` in javascript. You can use `db.collection.find().sort({_id:-1})` – Ashwanth Madhav Mar 18 '19 at 06:45

1 Answers1

2

Use sort when querying.

Just use db.collection.find().sort({_id:-1}).

You are saving documents to collection. It is not like push or unshift in javascript.

Ashwanth Madhav
  • 1,084
  • 1
  • 9
  • 21