How to delete all documents in mongodb collection in java - java

I want to delete all documents in a collection in java. Here is my code:
MongoClient client = new MongoClient("10.0.2.113" , 27017);
MongoDatabase db = client.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());
Is this the correct way to do this?
I am using MongoDB 3.0.2

Using API >= 3.0:
MongoClient mongoClient = new MongoClient("127.0.0.1" , 27017);
MongoDatabase db = mongoClient.getDatabase("maindb");
db.getCollection("mainCollection").deleteMany(new Document());
To drop the collection (documents and indexes) you still can use:
db.getCollection("mainCollection").drop();
see https://docs.mongodb.org/getting-started/java/remove/#remove-all-documents

To remove all documents use the BasicDBObject or DBCursor as follows:
MongoClient client = new MongoClient("10.0.2.113" , 27017);
MongoDatabase db = client.getDatabase("maindb");
MongoCollection collection = db.getCollection("mainCollection")
BasicDBObject document = new BasicDBObject();
// Delete All documents from collection Using blank BasicDBObject
collection.deleteMany(document);
// Delete All documents from collection using DBCursor
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
collection.remove(cursor.next());
}

If you want to remove all documents in collection then used below code :
db.getCollection("mainCollection").remove(new BasicDBObject());
Or If you want to drop whole collection then used this :
db.getCollection("mainCollection").drop();

For newer mongodb drivers you can use FindIterable to remove all documents in collection.
FindIterable<Document> findIterable = collection.find();
for (Document document : findIterable) {
collection.deleteMany(document);
}

Related

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.

How can I get only the objectId of document in mongodb using java

I want to get only the objectId from mongodb with matched crieteria.I can get it with dbobject and cursor method.But I used mongo client here and have no idea how to do it.
Thanking you
MongoClient client = new MongoClient("localhost", 27017);
MongoDatabase database = client.getDatabase("baazaronline");
MongoCollection<Document> collection = database
.getCollection("Attribute");
Bson filter = new Document("attcode", attcode);
Bson newValue = new Document("DefautV", DefautV).append("IVSO", IVSO).append("UniqueV", UniqueV).append("ValuesR", ValuesR).append("Visiblename", Visiblename).append("citso", citso).append("values",values);
Bson updateOperationDocument = new Document("$set", newValue);
collection.updateOne(filter, updateOperationDocument);
client.close();
Use findOneAndUpdate which returns the Document as result and map the _id.
Something like
ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument).get("_id", ObjectId.class);
Update: Include Projection to limit the response to only contain _id field.
FindOneAndUpdateOptions findOneAndUpdateOptions = new FindOneAndUpdateOptions();
findOneAndUpdateOptions.projection(Projections.include("_id"));
ObjectId id = collection.findOneAndUpdate(filter, updateOperationDocument, findOneAndUpdateOptions).getObjectId("_id");

Create a 'contains' query using Java and MongoDB

I'm trying to follow this post to create a "contains" query in Java. The problem is it's giving me an error.
At the moment i have the following code:
MongoClient mongoClient = null;
DBCursor cursor = null;
mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB("bd-films");
DBCollection coll = db.getCollection("films");
DBObject query = new BasicDBObject({"title" : {$regex : "name"}});
cursor = coll.find(query);
The error it gives me is in the 'query' line:
Syntax error on token ""title"", invalid Label
Syntax error, insert ";" to complete Statement
Syntax error on token ")", delete this token
I use the cursor for inserting it into a JTable.
Driver: mongo-java-driver-3.4.2
Thanks in advance.
Use new Document and MongoCollection api's for java driver 3.x version.
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("bd-films");
MongoCollection<Document> coll = db.getCollection("films");
List<Document> results = coll.find(Filters.regex("title", "name")).into(new ArrayList<>())
For accesssing MongoCursor,
FindIterable<Document> results = coll.find(Filters.regex("title", "name"));
MongoCursor<Document> cursor = results.iterator();

Queries in java mongodb API

I am new to mongodb java api. I am trying to perform queries to my database. I ve read the database found the collections in it and I want to retrieve characteristics of users. My code:
ServerAddress serverAdr;
serverAdr = new ServerAddress(".. .. .., ...);
Twitter twitter = null;
MongoOptions options = new MongoOptions();
options.connectionsPerHost = 10;
MongoClient mongoClient = new MongoClient(.. ... ...", ...);
DB db = mongoClient.getDB("trendSetters");
System.out.println("Connect to database successfully");
//JSONObject content = getJSONFromFile("user.json");
Mongo mongo = null;
Set<String> colls = db.getCollectionNames();
mongo = new Mongo(serverAdr, options);
mongo.setWriteConcern(WriteConcern.SAFE);
DB db_se = mongo.getDB("iti_se");
DBCollection incollection = db_se.getCollection("cms_users_unique");
DBCollection outcollection = db_se.getCollection("cms_users_features");
for (String s : colls) {
System.out.println(s);
}
Now I want to perform queries to retrieve from all ids the usernames for example. How is it possible to do so in java mongodb API?
EDIT: What i ve tried
BasicDBObject query = new BasicDBObject();
DBCursor cursor;
query = new BasicDBObject("followers", new BasicDBObject("$gt", 1));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
However, it doesnot return nothing.
You asked: "I want to perform queries to retrieve from all ids the usernames for example."
To retrieve all documents from collection you can use find() method of the DBCollection.
DBCursor cursor;
cursor = incollection.find();
After that, you can get the field value by its name for each document as below
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
If you need to add more criterias to query documents:
BasicDBObject query1;
DBCursor cursor;
query1 = new BasicDBObject("age", new BasicDBObject("$gt", 25));
cursor = incollection.find(query1);
while(cursor.hasNext()){
System.out.println(cursor.next().get("username"));
}
DBCollections objects have method find which takes mainly a DBObject argument. For instance, if you want to find users with age > 50 this can help you.
query = new BasicDBObject("age", new BasicDBObject("$gt", 50));
cursor = incollection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
BasicDBObject take first argument, that is a field, and second argument that is another BasicDBObject or a value. With composition of these objects you can build any query.
I recommend you take a look at MongoDB Documentation, it's pretty good.
Mongo Java Driver http://docs.mongodb.org/ecosystem/drivers/java/
See Javadoc. http://api.mongodb.org/java/current/

add DBCursor to memcached

I have following codes:
mongoClient = new MongoClient( "localhost" , 27017 );
db = mongoClient.getDB("hcm");
DBCollection coll = db.getCollection("segment_cell_details");
BasicDBObject query = new BasicDBObject("cell_x", cell_x).append("cell_y", cell_y);
DBCursor cursor = coll.find(query);
Next, I want to add DBCursor in memcached :
c = new MemcachedClient(AddrUtil.getAddresses("localhost:11211"));
c.add("Key", 3600, cursor);
Then, System prints out "Non-serializable object error"
So, how can I add the result of query to memcached ?
The cursor is an iterator that lazily loads the results. You need to add the results not the iterator. I recommend adding them as serialised JSON.
while (cursor.hasNext())
c.add("key",3600,cursor.next().toString());

Categories