I am using MongoDB and pymongo
to create a database and store data in them. I have a list that I wish to store in a database. And as far as I understand, I would have to use Python dict to do so and it gets stored as an array in the database. Now after storing it, to perform other operations such as plotting, mathematical operations etc. I want to set that array as a variable. But I cannot find a way to do so. Simply setting that array as a list/array variable is good enough. The variable 'results' does not print the array.
import pymongo
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db= client['l']
collection=db['data']
x= [1,2,3,4,5]
record = {'_id': 'x', 'values': x}
db.collection.insert_one(record)
results= collection.find({'values':x})
CodePudding user response:
First, i guess your database name is l
and the collection in that database is data
. To insert in your collection change your insert_one
line into something like this :
#one way
collection.insert_one(record)
#another way
client['l']['data'].insert_one(record)
You can also make some kind of mix using dot notation or array notation.
Then :
results
is a Cursor instance on which you can iterate to have the documents.
So you can try : results = [collection.find({'values':x})]
to have the list of all the document matching your query.
CodePudding user response:
Here's an ipython
session showing how you can retrieve your stored "values"
.
$ ipython
Python 3.10.9 (main, Dec 7 2022, 00:00:00) [GCC 12.2.1 20221121 (Red Hat 12.2.1-4)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.8.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from pymongo import MongoClient
In [2]: client = MongoClient("mongodb://localhost:27017/")
In [3]: collection = client["l"]["data"]
In [4]: x= [1,2,3,4,5]
...: record = {'_id': 'x', 'values': x}
In [5]: cursor = collection.insert_one(record)
In [6]: print(cursor.acknowledged)
True
In [7]: cursor = collection.find_one({"_id": "x"})
In [8]: print(cursor["values"])
[1, 2, 3, 4, 5]