A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.mongodb.com/docs/languages/python/pymongo-driver/current/crud/query/specify-query/ below:

Specify a Query - PyMongo Driver v4.13

In this guide, you can learn how to specify a query by using PyMongo.

You can refine the set of documents that a query returns by creating a query filter. A query filter is an expression that specifies the search criteria MongoDB uses to match documents in a read or write operation. In a query filter, you can prompt the driver to search for documents with an exact match to your query, or you can compose query filters to express more complex matching criteria.

The examples in this guide run operations on a collection called fruits that contains the following documents:

{ "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },{ "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },{ "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },

The following code example shows how to create a database and collection, then insert the sample documents into your collection. Select the Synchronous or Asynchronous tab to see the corresponding code:

from pymongo import MongoClienturi = "<connection string URI>"client = MongoClient(uri)try:    database = client["sample_fruit"]    collection = database["fruits"]    collection.insert_many([        { "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },        { "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },        { "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },        { "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },    ])    client.close()except Exception as e:    raise Exception("Error inserting documents: ", e)
from pymongo import AsyncMongoClienturi = "<connection string URI>"client = AsyncMongoClient(uri)try:    database = client["sample_fruit"]    collection = database["fruits"]    await collection.insert_many([        { "_id": 1, "name": "apples", "qty": 5, "rating": 3, "color": "red", "type": ["fuji", "honeycrisp"] },        { "_id": 2, "name": "bananas", "qty": 7, "rating": 4, "color": "yellow", "type": ["cavendish"] },        { "_id": 3, "name": "oranges", "qty": 6, "rating": 2, "type": ["naval", "mandarin"] },        { "_id": 4, "name": "pineapple", "qty": 3, "rating": 5, "color": "yellow" },    ])    await client.close()except Exception as e:    raise Exception("Error inserting documents: ", e)

Literal value queries return documents with an exact match to your query filter.

The following example specifies a query filter as a parameter to the find() method. The code returns all documents with a color field value of "yellow":

results = collection.find({ "color": "yellow" })
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}
Tip Find All Documents

To find all documents in a collection, call the find() method and pass it an empty query filter. The following example finds all documents in a collection:

results = collection.find({})

Comparison operators evaluate a document field value against a specified value in your query filter. The following is a list of common comparison operators:

To view a full list of comparison operators, see the Comparison Query Operators guide in the MongoDB Server manual.

The following example specifies a comparison operator in a query filter as a parameter to the find() method. The code returns all documents with a rating field value greater than 2:

results = collection.find({ "rating": { "$gt" : 2 }})for f in results:    print(f) 
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}
results = collection.find({ "rating": { "$gt" : 2 }})async for f in results:    print(f) 
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

Logical operators match documents by using logic applied to the results of two or more sets of expressions. The following is a list of logical operators:

To learn more about logical operators, see the Logical Query Operators guide in the MongoDB Server manual.

The following example specifies a logical operator in a query filter as a parameter to the find() method. The code returns all documents with a qty field value greater than 5 or a color field value of "yellow". Select the Synchronous or Asynchronous tab to see the corresponding code:

results = collection.find({     "$or": [        { "qty": { "$gt": 5 }},        { "color": "yellow" }    ]})for f in results:    print(f)
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}
results = collection.find({     "$or": [        { "qty": { "$gt": 5 }},        { "color": "yellow" }    ]})async for f in results:    print(f)
{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

Array operators match documents based on the value or quantity of elements in an array field. The following is a list of available array operators:

To learn more about array operators, see the Array Query Operators guide in the MongoDB Server manual.

The following example specifies an array operator in a query filter as a parameter to the find() method. The code returns all documents with a type array field containing 2 elements. Select the Synchronous or Asynchronous tab to see the corresponding code:

results = collection.find({    "type" : { "$size": 2 }})for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}
results = collection.find({    "type" : { "$size": 2 }})async for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 3, 'name': 'oranges', 'qty': 6, 'rating': 2, 'type': ['naval', 'mandarin']}

Element operators query data based on the presence or type of a field.

To learn more about element operators, see the Element Query Operators guide in the MongoDB Server manual.

The following example specifies an element operator in a query filter as a parameter to the find() method. The code returns all documents that have a color field. Select the Synchronous or Asynchronous tab to see the corresponding code:

results = collection.find( { "color" : { "$exists": "true" }} )for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}
results = collection.find( { "color" : { "$exists": "true" }} )async for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 2, 'name': 'bananas', 'qty': 7, 'rating': 4, 'color': 'yellow', 'type': ['cavendish']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

Evaluation operators return data based on evaluations of either individual fields or the entire collection's documents.

The following is a list of common evaluation operators:

To view a full list of evaluation operators, see the Evaluation Query Operators guide in the MongoDB Server manual.

The following example specifies an evaluation operator in a query filter as a parameter to the find() method. The code uses a regular expression to return all documents with a name field value that has at least two consecutive "p" characters. Select the Synchronous or Asynchronous tab to see the corresponding code:

results = collection.find({ "name" : { "$regex" : "p{2,}" }} )for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}
results = collection.find({ "name" : { "$regex" : "p{2,}" }} )async for f in results:    print(f)
{'_id': 1, 'name': 'apples', 'qty': 5, 'rating': 3, 'color': 'red', 'type': ['fuji', 'honeycrisp']}{'_id': 4, 'name': 'pineapple', 'qty': 3, 'rating': 5, 'color': 'yellow'}

It's common in web applications to encode documents' ObjectIds in URLs, as shown in the following code example:

"/posts/50b3bda58a02fb9a84d8991e"

Your web framework passes the ObjectId part of the URL to your request handler as a string. You must convert the string to an ObjectId instance before passing it to the find_one() method.

The following code example shows how to perform this conversion in a Flask application. The process is similar for other web frameworks.

from pymongo import MongoClientfrom bson.objectid import ObjectIdfrom flask import Flask, render_templateclient = MongoClient()app = Flask(__name__)@app.route("/posts/<_id>")def show_post(_id):      post = client.db.posts.find_one({'_id': ObjectId(_id)})   return render_template('post.html', post=post)if __name__ == "__main__":    app.run()

To learn more about querying documents, see the Query Documents guide in the MongoDB Server manual.

To learn more about retrieving documents with PyMongo, see Find Documents.

To learn more about any of the methods or types discussed in this guide, see the following API documentation:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4