简体   繁体   中英

How to insert a document at first position in MongoDB

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM