Delete all documents in a collection with Springdata mongo Query - mongodb

I want to implement a delete method which deletes all the documents in a collection. I am using mongo db with Spring Data.This could be done using db.myCollection.remove({}) in Mongo shell. But I want to write a method in my data access layer to do this.I am not using MongodbTemplate in my Dao class. I want to know how can I do this with Query.
Query query = new Query();
Could anybody please tell me how can I do it.

You can use MongoTemplate directly
mongoTemplate.remove(new Query(), collectionName);

Use MongoRepository's deleteAll(). Utilizes mongoTemplate behind the scene to call the remove method.
From calling method someRepository.deleteAll()
Drop collection may be efficient as other answer has noted. For that you will need to use MongoTemplate directly and call dropCollection with entity class or collection name.

You can drop the collection and create it again:
mongoTemplate.dropCollection("collectionName");
mongoTemplate.createCollection("collectionName");

You'd better drop the entire collection (if possible) than deleting all documents. For performance and allocation sake.
You can try something such as:
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection collection = db.getCollection("test_collection");
collection.drop();
If you do want to delete all (I think), instead of:
collection.drop();
use:
Bson filter = new Document();
collection.deleteMany(filter);
Query is part of spring-data-mongodb, if you can't use a MongoTemplate, probably Query is irrelevant as well.

If you have considerable changes in schema, better is to drop the collection.
MongoTemplate.dropCollection(collectionName).
But the requirement is to delete all documents you have use
MongoTemplate.remove(new Query(), collectionName)or
CrudRepository.deleteAll()

If all collections are to be deleted, this could also be done:
mongoTemplate.collectionNames
.forEach { mongoTemplate.dropCollection(it) }

Related

Duplicate the documents in same collection in mongo

Is there a way to duplicate the records in a collection into the same collection ? I am trying to generate lots of records and hence this is needed.
If you just want to duplicate easy way is like below
db.col1.find({},{_id:0}).forEach(function(doc){db.col1.save(doc)});
A quick but maybe not the most efficient way to do that could be:
Get all the documents of the collection
For each one re-write the ObjectId with a new value
Insert the modified document inside the collection
With mongo shell you could do that using the forEach as follows:
db.getCollection('YOUR_COLLECTION').find({}).forEach(
function(doc){
doc._id = new ObjectId();
db.getCollection('YOUR_COLLECTION').insert(doc);
}
)
This way, each time you run this query, all the documents in the collection are duplicated.

How to create a collection in MongoDB using SPRING data

Am using Spring-Data-Mongo to access do CRUD operations on my mongo database. I execute the below line
DB db = mongoTemplate.getDb()
When am in debug mode I can see that db._collections properties has 4 values (collections that I inserted). But when I query for
db.getCollectionNames()
I get zero collections back. Why is that? Same is also true when I do
db.getCollection("collectionName")
But I know the collections do exists because when I do something like
mongoTemplate.createCollection("collectionName");
I get an exception saying that collection already exists. Can anyone please explain what I might be missing
MongoTemplate provides a few methods for managing collections. The following example demonstrates some of the methods:
DBCollection collection = null;
if (!mongoTemplate.getCollectionNames().contains("collectionName")) {
collection = mongoTemplate.createCollection("collectionName");
}
mongoTemplate.dropCollection("collectionName");
In the above, getCollectionNames() returns a set of collection names and dropCollection() drops the collection.
Use MongoClient, MongoDatabase, and MongoIterable of com.mongodb.client and com.mongodb package.
MongoClient client = MongoClient(<host>, port);
MongoDatabase db = client.getDatabase(<Name of the database>);
MongoIterable<String> = db.listCollectionNames();
And now you can iterate over all the names of the collections.
Additionally, you even can use MongoCollection class to get the Document from the specified collection. The getCollection() will create collection if not present.
MongoCollection<Document> collection = db.getCollection(<Collection name>);

Is it possible to perform multiple DB operations on two sets of documents in single transaction in MongoDB using morphia

Can the following two update operations take place in one single transaction?
Query<Group> query1 = createQuery().disableValidation().field("users").equal(user.getUserId()).retrievedFields(true, "_id","users");
UpdateOperations<Group> ops1 = createUpdateOperations().removeAll("users", user);
update(query1, ops1);
Query<Group> query = createQuery().field("_id").in(groupList);
UpdateOperations<Group> ops = createUpdateOperations().add("users", user);
update(query, ops);
There are no multidocument transactions in mongodb. Writes to a single document are atomic, however. So no, there is no way to do that via morphia either.

MongoDB Java Driver creating Database and Collection

i was testing how to create database and collection mongo java driver.
MongoClient client = new MongoClient("localhost",27017);
DB db = client.getDB("ow");
DBCollection collection = db.getCollection("documents");
collection.save(new BasicDBObject("_id",1));
collection.remove(new BasicDBObject("_id",1));
boolean result = db.collectionExists("documents");
assertTrue(result);
assertNotNull(collection);
client.close();
I would prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first document is inserted.
My question is is this understanding correct ? Is above code correct was of creating collection or database.
prefer to use createCollection method on the DB object, but found that it does not create database / collection unless the first
document is inserted.
MongoDB creates a collection implicitly when the first document is saved into a collection. The createCollection() method explicitly creates a collection only and only if an options object is passed to it as an argument.
Now this makes sense. The options parameter can take in one or more arguments to decide the characteristics of the collection we want to create such as capped,autoIndexId,size,usePowerOf2Sizes,max no. of documents.
If we do not specify any of these options, the default behavior would take precedence, i.e create a collection lazily whenever the first insert is made, with default settings.
So if we want a collection whose characteristics we are going to define, then we can pass these characteristics as a DBObject to the createCollections() method and our collection would be created. Below is an example of how to pass the options.
BasicDBObject options = new BasicDBObject();
options.put("size", 12121212);
db.createCollection("hello", options);
Is above code correct was of creating collection or database.
Yes. It allows mongodb to apply the default configuration for your collection. Unless you want to set the
max,size,autoIndexId,capped,usePowerOf2Sizes properties for your new collection, this is fine.
Refer: http://docs.mongodb.org/manual/reference/method/db.createCollection/

Updating index in Lucene.NET

I am doing a POC on Search using Lucene.NET.
I fire a stored procedure which fetches around 50000 records from the database.
Thses records I put in the Lucene Index.
Now when the records in database changes, how to update the Lucene index.
Deleting the entire previous indexed and creating a new one will take a lot of time.
I want to append the new records from the database to the existing index.
How can I achieve this.
Any ideas ???
Thanks,
Aneesh
Just use lucene AddDocument method, something like this :
IndexWriter iw = new IndexWriter(folder, GetAnalyzer(), false);
try
{
Document luceneDoc = new Document();
/// add fields to the lucene document
iw.AddDocument(luceneDoc);
}
finally
{
iw.Close();
}