Python MongoDB zoeken

In MongoDB gebruiken we de find- en findOne-methoden om gegevens in een collectie te vinden.

Net zoals een SELECT-statement wordt gebruikt om gegevens uit een tabel in een MySQL-database te vinden.

Een item vinden

Om gegevens te selecteren uit een collectie in MongoDB, kunnen we find_one() Methode.

find_one() De methode retourneert het eerste overeenkomende item in de selectie.

Example

Vind het eerste document in de "customers"-collectie:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)

Run Example

Alles vinden

Om gegevens van een tabel in MongoDB te selecteren, kunnen we ook find() Methode.

find() De methode retourneert alle overeenkomende items in de selectie.

find() De eerste parameter van de methode is het query-object. In dit voorbeeld gebruiken we een leeg query-object, dat alle documenten in de collectie selecteert.

find() De methode biedt geen parameters die hetzelfde resultaat geven als SELECT * in MySQL.

Example

Retourneert alle documenten in de "customers"-collectie en print elk document:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
  print(x)

Run Example

Returneert alleen bepaalde velden

find() De tweede parameter van de methode beschrijft het object dat de velden bevat die in de resultaten worden opgenomen.

This parameter is optional. If omitted, all fields will be included in the results.

Example

Only return name and address, not _ids:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
  print(x)

Run Example

It is not allowed to specify 0 and 1 values at the same time in the same object (unless one of the fields is the _id field). If a field with a value of 0 is specified, all other fields will have a value of 1, and vice versa:

Example

This example excludes "address" from the results:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "address": 0 }):
  print(x)

Run Example

Example

An error will occur if 0 and 1 values are specified at the same time in the same object (unless one of the fields is the _id field):

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "name": 1, "address": 0 }):
  print(x)