I am new to pymongo and mongo db and created a cluster with the database and the collection I need. I have added data to the Collection but i'm having trouble retrieving the data as individual values. I need to find the only record where the Gender is female and check the Name belonging to that record, Not been able to find help online. Sorry if it's a noob question
import pymongo
client = pymongo.MongoClient('mongodb+srv://#test-v6kig.mongodb.net/admin')
testdb = client['mytestdb']
testcol = testdb['mytestcol']
myquery = { "Gender" : "Female" }
data = testcol.find(myquery)
if "Need to get value of NAME attribute in the data record" == "Sushmit":
print("Y")
else:
print("N")
Any help is appreciated :)
use find_one methods and pass to it the id parameter like this:
single_value= testcol.find_one({'id'})
find_one always returns a single result which is a JSON document. find always returns a cursor (even if there is only a single result or no results). So to get the results from your find query you would do:
cursor=pymongo.find(myquery)
for doc in cursor:
print(doc)
Related
I want to get the document id, when I do and upsert, currently flask-pymongo only returns object Id when the document is inserted but not when is updated.
I am using the following code:
a = mongo.db.abcd.update_one(
{'abcd': 'abcd1'}, {"$set": {"abcd": "abcd2"}}, upsert=True)
for value in a.raw_result.items():
print(value)
There are any way to return the id?
Thanks
update_one() returns a instance of UpdateResult (https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.update_one) and UpdateResult have a property upserted_id.
The documentation say: The _id of the inserted document if an upsert took place. Otherwise None.
https://pymongo.readthedocs.io/en/stable/api/pymongo/results.html#pymongo.results.UpdateResult.upserted_id
Looks like that is what you need
I am trying to update all properties of the record/object which is stored in MongoDB, now I am trying to do like this.
Deleted the object, but keeping the ID of the object being deleted.
Create a new object with the same ID which I have deleted.
Is it correct ? or What is they to do above objective using pymongo ?
mongo_object = {
_id : 123,
prop_key_1: some_value,
// ... many present
prop_key_n: some_value,
}
def delete(record):
doc = get_db().reviews.delete_many({"id" : record["_id"]})
print(doc.deleted_count)
# all key values are changed, mongo_object is changed except the id.
delete(mongo_object)
db.collection_name.insert_one(mongo_object)
But above code is not deleting the object, the doc.deleted_count is 0.
db.collection_name.update_one({"_id" : record["_id"]}, new_data}
just use update without $set , the document will get replaced completely without changing the _id
from bson.objectid import ObjectId
def replace_one(record):
result = client.test_db.test_collection.replace_one({"_id":ObjectId(record["_id"])}, record,upsert=True)
print(result.matched_count)
What is the correct way to query MongoDB for _id using string by using Python?
Pymongo doc - http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one
I want to find the _id of a document of a collection (mycol) where "name":"John". I have inserted the document but want to find the _id of document. Is it possible ? I am trying as
result = db.mycol.find({"_id": {"name": "John"}})
But it is returning a cursor object.
pymongo.cursor.Cursor object at 0x00000000030E3DD8>
Then I tried as
for itm in result:
print (itm)
But it is not printing anything.
Try it like that
result = db.mycol.find({"name": "John"})
for item in result:
print(item['_id'])
Just have a look at the docs to see how to use pymongo
I want to select all data or select with conditional in table random but I can't find any guide in MongoDB in Python to do this.
And I can't show all data was select.
Here my code:
def mongoSelectStatement(result_queue):
client = MongoClient('mongodb://localhost:27017')
db = client.random
cursor = db.random.find({"gia_tri": "0.5748676522161966"})
# cursor = db.random.find()
inserted_documents_count = cursor.count()
for document in cursor:
result_queue.put(document)
There is a quite comprehensive documentation for mongodb. For python (Pymongo) here is the URL: https://api.mongodb.org/python/current/
Note: Consider the version you are running. Since the latest version has new features and functions.
To verify pymongo version you are using execute the following:
import pymongo
pymongo.version
Now. Regarding the select query you asked for. As far as I can tell the code you presented is fine. Here is the select structure in mongodb.
First off it is called find().
In pymongo; if you want to select specific rows( not really rows in mongodb they are called documents. I am saying rows to make it easy to understand. I am assuming you are comparing mongodb to SQL); alright so If you want to select specific document from the table (called collection in mongodb) use the following structure (I will use random as collection name; also assuming that the random table has the following attributes: age:10, type:ninja, class:black, level:1903):
db.random.find({ "age":"10" }) This will return all documents that have age 10 in them.
you could add more conditions simply by separating with commas
db.random.find({ "age":"10", "type":"ninja" }) This will select all data with age 10 and type ninja.
if you want to get all data just leave empty as:
db.random.find({})
Now the previous examples display everything (age, type, class, level and _id). If you want to display specific attributes say only the age you will have to add another argument to find called projection eg: (1 is show, 0 is do not show):
{'age':1}
Note here that this returns age as well as _id. _id is always returned by default. You have to explicitly tell it not to returning it as:
db.random.find({ "age":"10", "name":"ninja" }, {"age":1, "_id":0} )
I hope that could get you started.
Take a look at the documentation is very thorough.
I'm new to python and have mongo db and im using pymongo to find an data in one of the many collection and if i found one i want to stop the and return true ?
Pymongo has a find_one() method.
Check it out here.
You can use the following to find weather the record is there or not:
test = bool(db.collection_1.find_one({'key': key}) or db.collection_2.find_one({'key1':) key1})
if test:
print "found"
else:
print "not found"