Get the App
SLTechnology News&Howtos  ›  Database  › 

Query data from mongodb

Shulou Source: shulou.com Published: 2022-06-01 21:57:13 09月23日 Update

Connect to the mongodb:

Public class GenericMga {private DB db; public DB getDB () {return this.db;} public void setDB (DB db) {this.db = db;}} DBCollection coll= null;coll=getDB (). GetCollection ("collName"); / / the save name is equivalent to the table name of MySQL

Create query criteria:

BasicDBObject query = new BasicDBObject (); query.append ("type", type); / / "type" queries all data that meets the type=type criteria for the fields in the table / / queries the data query.append ("time", new BasicDBObject ("$gte", searchStartTime) .append ("$lte", searchEndTime)) between time and the fields in the table ("time", new BasicDBObject ("$gte", searchStartTime) .append ("$lte", searchEndTime); query.append ("role", "{$exists:true}"); / / queries the data DBCursor cursor = coll.find (query) that exists in the role field While (cursor.hasNext ()) {cursor.next ();}

If you only want to query a field or fields, you can create a query as another query condition:

BasicDBObject query1 = new BasicDBObject (); query1.append ("user", 1); / / means only user is queried (default _ id also exists. If you don't want it, you can set it as follows) query1.append ("_ id", 0); / / does not show the _ id field DBCursor cursor = coll.find (query,query1); while (cursor.hasNext ()) {cursor.next ();}

Query the document: db.DeviceInfo.find that exists in the role field ({"role": {$exists: true}})

Tags: Query field data condition between name time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Redmi Xiaomi Docker vpn