Joe
Joe

Reputation: 35

How to select all data in 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)

Upvotes: 1

Views: 6565

Answers (1)

ibininja
ibininja

Reputation: 1217

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.

Upvotes: 2

Related Questions