why mongo is fetching results even after deleting the collection? - mongodb

using pymongo i have deleted a particular collection. when i query the database using mongoengine x.objects.get(y="something") is still showing up with the deleted result.
anyone please help me with this.. Thanks in advance.

You could try using the drop method:
from pymongo import Connection
connection = Connection('localhost', 27017) #Connect to mongodb
print(connection.database_names()) #Return a list of db, equal to: > show dbs
db = connection['testdb1'] #equal to: > use testdb1
print(db.collection_names()) #Return a list of collections in 'testdb1'
print("posts" in db.collection_names()) #Check if collection "posts"
# exists in db (testdb1)
collection = db['coll']
print(collection.count() == 0) #Check if collection named 'coll' is empty
collection.drop() #Delete (drop) collection named 'coll' from db

Related

MongoDB import to different collections set by a field

I have a file called data.json and extracted with mongoexport, with the following structure:
{"id":"63","name":"rcontent","table":"modules"}
{"id":"81","name":"choicegroup","table":"modules"}
{"id":"681","course":"1242","name":"Requeriments del curs","timemodified":"1388667164","table":"page"}
{"id":"682","course":"1242","name":"Guia d'estudi","timemodified":"1374183513","table":"page"}
What I need is to import this file into my local mongodb with a command like mongoimport or with pymongo, but storing every line in the collection named after the table value.
For example, the collection modules would contain the documents
{"id":"63","name":"rcontent"} and {"id":"81","name":"choicegroup"}
I've tried with mongoimport but I haven't seen any option which allows that. Does anyone know if there is a command or a method to do that?
Thank you
The basic steps for this using python are:
parse the data.json file to create python objects
extract the table key value pair from each document object
insert the remaining doc into a pymongo collection
Thankfully, pymongo makes this pretty straightforward, as below:
import json
from pymongo import MongoClient
client = MongoClient() # this will use default port and host
db = client['test-db'] # select the db to use
with open("data.json", "r") as json_f:
for str_doc in json_f.readlines():
doc = json.loads(str_doc)
table = doc.pop("table") # remove the 'table' key
db[table].insert(doc)

Determine whether collection in MongoDB exists in Python

I want to know whether collections of specific names exists in the MongoDB. How can I achieve this programmatically in Python. On searching about the same, I got to know how to do that from MongoDB shell but nothing useful for doing the same in Python.
You can use the method to retrieve and check if your collection exists or not from the comment given by the #Alex like this:
Method 1:
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
list_of_collections = db.list_collection_names() # Return a list of collections in 'test_db'
print("posts" in list_of_collections) # Check if collection "posts" exists in db (test_db)
Or, you can validate a collection with validate_collection() (documentation) This returns an error (pymongo.errors.OperationFailure) if the collection doesn't exist. With this method, you can also catch that exception and do whatever you want.
Method 2:
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
try:
db.validate_collection("random_collection_name") # Try to validate a collection
except pymongo.errors.OperationFailure: # If the collection doesn't exist
print("This collection doesn't exist")

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

JMETER - MongoDB delete record sample script for jmeter

Can someone help me on groovy sample code for deleting a record from a MongoDB collection ? Thanks in advance.
Prior to removing an object your need to find one.
Full sample code (my expectation is that you're interested in the last line only, but just in case):
import com.mongodb.* // import all the mongodb.* stuff
import org.apache.jmeter.protocol.mongodb.config.MongoDBHolder;
DB db = MongoDBHolder.getDBFromSource("MongoDBSourceName", "DatabaseName");
DBCollection collection = db.getCollection("CollectionName");
BasicDBObject query = new BasicDBObject("name", "value"); // create DBObject holding the query
DBObject result = collection.findOne(query); // find the document
collection.remove(result); //delete the document
References:
DBCollection class JavaDoc (see remove() and findAndRemove() methods in particular)
How to Load Test MongoDB with JMeter

mongodb collection

I want to list all the collection, created under my database. I know the query
db.getCollectionNames();
But it listing only - [ "system.indexes", "system.users" ]
I tried
show collections
it listed following - system.indexes, system.users
It is not showing me my collections. How can i see all my collections ?
To see all the collections in the current database using the mongo shell:
db.getCollectionNames() returns the collections in the current database as a JavaScript array
show collections prints the collections in the current database as a list
If you aren't seeing the expected collections, you can check the current database with:
db.getName()
If you want to see all collections in all databases, here's some JavaScript that should do the trick:
db.adminCommand("listDatabases").databases.forEach(function (d) {
sdb = db.getSiblingDB(d.name);
print("Collections in database: "+d.name);
printjson(sdb.getCollectionNames())
print("")
})
I think there must be more than one driver out there.
I did
npm install mongodb
to install the driver and I think the driver I get is the one documented here
http://mongodb.github.io/node-mongodb-native/2.0/api/
It does not have getCollectionNames() or collectionNames() but it does have collections()