I am inserting a document in MongoDB collection using below code:
try:
x = coll.insert_one(data_dict).inserted_id
print(x)
except Exception as e:
log.error("Exception at saving data for db {}".format(cid))
log.error(e)
This inserts document in collection and mongo db creates its own object id as shown in below image:
_id is automatically created. Is it possible to insert your own id here. How can we do that.
One way of doing this is to create _id in data_dict()
data_dict['_id'] = uuid.uuid4()
and then save the data in db. This then saves the _id with the uuid but the data type is also saved as UUID and I want to save it as ObjectID. Can anyone please help me.
Yes you have to make your own objectid with BSON module.
from bson.objectid import ObjectId
Then you can create your own objectid and use it for creation or to insert. This should be a comment but I dont have the required rep.
Related
it is my first time to use mongoengine, I know the ORM concept.
I want to know may I get the data in one DB and using the same object to store in another DB??
class User(Document):
email = EmailField(required=True, unique= True)
salary = IntField(require=True)
connect(alias='default',db='tumblelog')
connect(alias='testdb',db='testdb')
users = User.objects
with switch_db(User,'testdb') as User:
for user in users:
User(email=user.email,salary=user.email).save # it works
user.save() #doesn't works
I've found out that by using ORM to get a data from one DB, it will create an object unique to the DB you get it from. You won't be able to use the same object to store it into another DB.
What I would suggest is that you initialise an empty object, for example User, for the other DB and fill it with values from the original object and then store it.
You might want to have a look at this question. Sequelize: Using Multiple Databases
I am trying to print all the object ids in a collection I have in mongoDB. I understand how to convert the ObjectId to a string, however I am not sure how to actually make a call to list all the object ids.
I tried the following from pymongo documentation but nothing happens because I have 4 ObjectIds
def get(post_id):
Document=client.db.collection.find_one({'_id':ObjectId(post_id)})
return Document
from bson import ObjectId
id = "5fec2c0b348df9f22156cc07"
objInstance = ObjectId(id)
collection.find_one({"_id": objInstance})
# below line works same as the above
collection.find_one({"_id": ObjectId(id)})
collection.find_one(ObjectId(id))
bson should already been installed once you installed pymongo
I update collection in mongo db . but cant find matches. this is my code.
collection = MongoClient()["blog"]["users"]
client = MongoClient()
db = client.blog
result = db.test.update_many({"_id": '12345'}, {"$set": {"email":
"dmitry"}})
print (result.matched_count)
You are trying to update the _id field which is immutable, you will need to create a new entry and delete the old one by storing the document into a variable and then saving it with the new _id and then removing the old document.
I am new to python and mongo db, i have a dict called data and i wanna use the keys to query the database called db.
def update_db(data, db):
for key in data:
x=db.find({'label':key})
for a in x:
print a
I get the error message that find() does not exist.
Anyone can give me input on my problem ?
There is no find method in database object. You should search documents in some collection, not in database. Database has collections like SQL database has tables. Collections have documents, like SQL tables have rows of data. E.g. if you have users collection:
def update_db(data, db):
for key in data:
users = db.users
matchedUsers = users.find({'label':key})
for user in matchedUsers:
print user
Future reading PyMongo tutorial
im trying to run this python-django code below, but am getting a blank output
SitePaths = PathsOfDomain.objects.filter(pathToScan__contains="www.myapp.com")
return SitePaths
PathsOfDomain is the object representation of a db table.
I'm trying to iterate through a db field name pathToScan and output each value
If someone can please shed some light on this.
Thank you.
If you meant to query for matching PathsOfDomain rows in the database, use the .objects attribute to create a query set:
SitePaths = PathsOfDomain.objects.filter(FKtoTld__id=domain_in_session)
See Making queries in the Django documentation.
Alternatively, if there is a foreign key relationship between the Tld and PathsOfDomain objects, use the related objects manager instead:
SitePaths = domain_in_session.pathsofdomain_set.all()