Sort values ​​by date in mongodb

I am new to mongodb and I am trying to sort all my lines by date. I have records from mixed sources, and I try to sort them separately. I did not update dateCreatedwhen writing to db for some records. Later I found, and I added dateCreatedto all my db entries. Let's say I have a total of 4000 entries, in the first 1000 I do not dateCreated. The last 3000 have this column. Here I am trying to get the latest updated record using a column dateCreated. Here is my code.

db.person.find({"source":"Naukri"}&{dateCreated:{$exists:true}}).sort({dateCreated: 1}).limit(10)

This code returns me some results (out of 1000 entries) where I don't see the column at all dateCreated. Moreover, if I change (-1) here {dateCreated: -1}, I get results from another source, but not Naukri.

So, I need help in this case,

  • How do I sort by dateCreatedto get the latest updated record and sources.

  • I am using the Java API to retrieve records from Mongo. I would appreciate if someone could help me find how I would use the same query with java.

Hope my question is clear. Thanks in advance.

+4
source share
2 answers

, ( , - ), , , find, , , . , , , SQL.

, . :

db.person.find({"source":"Naukri", dateCreated:{$exists:true}})
    .sort({dateCreated: -1})
    .limit(10)

, value "" dateCreated, -.

, mongoDB find . .

Java API , , , . API BasicDBObject, JSON . - , , QueryBuilder, . , .

Qaru . .

http://docs.mongodb.org/manual/tutorial/query-documents/

http://docs.mongodb.org/manual/reference/method/db.collection.find/

MongoDB java?

http://api.mongodb.org/java/2.2/com/mongodb/QueryBuilder.html

+2

. :

db.person.find({"source":"Naukri", dateCreated:{$exists:true}}).sort({dateCreated: 1}).limit(10)

Java :

Mongo mongo = ...
DB db = mongo.getDB("yourDbName");
DBCollection coll = db.getCollection("person");

DBObject query = new BasicDBObject();
query.put("source", "Naukri");
query.put("dateCreated", new BasicDBObject($exists : true));

DBCursor cur = coll.find(query).sort(new BasicDBObject("dateCreated", 1)).limit(10);    
while(cur.hasNext()) {
    DBObject obj = cur.next();
    // Get data from the result object here
}
+1

Source: https://habr.com/ru/post/1526301/


All Articles