Home > Database > MongoDB > How to insert Python objects in Mongodb?

How to insert Python objects in Mongodb?

PHPz
Release: 2023-09-02 21:37:02
forward
1245 people have browsed it

如何在 Mongodb 中插入 Python 对象?

You can use the pymongo library in Python to connect to a MongoDB database and use it to insert, update, delete, etc. objects in Python. The library supports Python datetime objects out of the box and you don't need to do anything special to insert dates in Mongo using PyMongo. For example,

Example

from pymongo import MongoClient
# This will try to connect to MongoDB on the default port and host
client = MongoClient()
db = client.test_database
# Insert the given dictionary to the objects collection:
result = db.objects.insert_one({"last_modified": datetime.datetime.utcnow()})
print("Object inserted!")
Copy after login

Output

This will give the output -

Object inserted!
Copy after login

Note- Always use datetime.datetime.utcnow(), which returns The current time in UTC, instead of datetime.datetime.now(), which returns the current local time.

The above is the detailed content of How to insert Python objects in Mongodb?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template