Read Data using Operators and Compound Queries

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    In the previous read guide, Read Data from MongoDB With Queries, you read data using embedded fields and dot notation. In this guide, you will:

    • read data from the inventory collection with MongoDB’s comparison operators.
    • combine query criteria to make compound queries

    Time required: 30 minutes

    What You’ll Need

    Warning

    If you are running MongoDB locally and have not enabled authentication, your MongoDB instance is not secure.

    Check Your Environment

    You will need to ensure that your MongoDB instance is running and accessible.

    Check that you have an Atlas account and have deployed a MongoDB database cluster. See Create an Atlas Account and Cluster for information on how to login and create a cluster in Atlas.

    To make sure that your MongoDB instance is running on Windows, run the following command from the Windows command prompt:

    tasklist /FI "IMAGENAME eq mongod.exe"
    

    If a mongod.exe instance is running, you will see something like:

    Image Name                     PID Session Name        Session#    Mem Usage
    ========================= ======== ================ =========== ============
    mongod.exe                    8716 Console                    1      9,508 K
    

    To make sure your MongoDB instance is running on Mac, run the following command from your terminal:

    ps -e | grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    To make sure your MongoDB instance is running on Linux, run the following command from your terminal:

    ps -e| grep 'mongod'
    

    If a mongod instance is running, you will see something like:

    89780 ttys026    0:53.48 ./mongod
    

    Procedure

    Read Data with Embedded Fields and Comparison Operators

    In this exercise, you will read data using comparison operators.

    1

    Connect to your MongoDB instance.

    Select the operating system platform on which you are running the MongoDB client you have selected.

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo.exe <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    Pass the URI to the mongo shell followed by the --password option. You will then be prompted for your password.

    mongo <URISTRING_SHELL_NOUSER>
    

    If you wish to manually configure your Compass connection, load Compass and select the New Connection link. You will see a form where you can enter connection information for MongoDB.

    Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.

    See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.

    If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

    ../../_images/connect-to-host.png

    You will be prompted to populate the connection dialog. Click Yes.

    You should then populate the password field with the proper password for your MongoDB user in the connection form.

    Note

    Errors related to connecting through Compass will appear in red at the top of the Connect screen.

    It’s a good idea to put your connection code in a class so that it can be reused.

    from pymongo import MongoClient
    
    class Connect(object):
        @staticmethod    
        def get_connection():
            return MongoClient("<URISTRING>")
    

    If your connection_string starts with mongodb+srv, you need to install the dnspython module with

    python -m pip install dnspython
    

    Now add code to call the class you just created.

    from connect import Connect
    from pymongo import MongoClient
    
    connection = Connect.get_connection()
    
        final String uriString = "<URISTRING>";
        MongoClientURI uri = new MongoClientURI(uriString);
        MongoClient mongoClient = new MongoClient(uri);
    
    const MongoClient = require('mongodb').MongoClient;
    const assert = require('assert');
    
    // Connection URL
    const url = '<URISTRING>';
    
    // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, client) {
      assert.equal(null, err);
      client.close();
    });
    

    The asyncio and pprint imports will be used as you add functionality to your example code.

    import motor.motor_asyncio
    import asyncio
    import pprint
    
    client = motor.motor_asyncio.AsyncIOMotorClient('<URISTRING>')
    

    The MongoDB.Bson package is used in CRUD operations, so you’ll import it here.

    using System;
    using MongoDB.Bson;
    using MongoDB.Driver;
    
    namespace csharptest
    {
        class Connect
        {
            static void Main(string[] args)
            {
               var client = new MongoClient("<URISTRING>");
            }
        }
    }
    
    2

    Switch to the test database.

    Switch to the database you wish to query. In this case we will be using test.

    To switch to the test database in the mongo shell, type

    use test
    

    If the database has not been created already, click the Create Database button.

    Screeenshot after connecting with the "Create Database" button.

    Select the test database on the left side of the Compass interface. Compass will list all of the collections in the database below the database name.

    Screenshot of the MongoDB Compass UI showing with the "test" database selected in the list of databases in the cluster.

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    MongoDatabase mongoDB = mongoClient.getDatabase("test");
    MongoCollection<Document> collection = mongoDB.getCollection("inventory");
    

    Within the connect block, set db to the test database.

    const db = client.db("test");
    

    To access the test database:

    db = client.test
    

    Switch to the test database and access the inventory collection.

    var database = client.GetDatabase("test");
    var collection = database.GetCollection<BsonDocument>("inventory");
    
    3

    Select documents using the less-than operator.

    The following example retrieves all documents from the inventory collection where the size.h field is less than 15. MongoDB uses dot notation to specify fields within embedded documents. size.h refers to the h field in the size document.

    myCursor = db.inventory.find( { "size.h": { $lt: 15 } } )
    

    Copy the following filter into the Compass query bar and click Find:

    { "size.h": { $lt: 15 } }
    
    cursor = db.inventory.find({"size.h": {"$lt": 15}})
    

    First you will need to create the MongoCollection object you would like to query against.

    MongoCollection<Document> collection = db.getCollection("inventory");
    

    Next pass the query document to the collection.find() method.

    findIterable = collection.find(lt("size.h", 15));
    
    var cursor = db.collection('inventory').find({ 
      "size.h": { $lt: 15 }
    });
    
    cursor = db.inventory.find({"size.h": {"$lt": 15}})
    

    For completeness, this is how you might wrap this call and run it with the asyncio event loop.

    async def do_retrieve_operator():
        cursor = db.inventory.find({"size.h": {"$lt": 15}})
        async for doc in cursor:
            pprint.pprint(doc)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_operator())
    
    var filter = Builders<BsonDocument>.Filter.Lt("size.h", 15);
    var result = collection.Find(filter).ToList();
    
    4

    Iterate over the results.

    By default, the shell will only show the first 20 documents and return a cursor. This is adequate when the result set only contains a few documents.

    If your result set is larger, to see all of the results of your query, iterate the cursor.

    while (myCursor.hasNext()) {
        print(tojson(myCursor.next()));
    }
    

    Note

    You can also manually iterate through the results by typing it when prompted by the shell.

    You will see a list of all of the documents that match your criteria in the query window.

    from pprint import pprint
    
    for inventory in cursor:
         pprint(inventory)
    

    You can implement a com.mongodb.Block to print the results of the iteration

    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    

    Then iterate the cursor for documents, passing the printBlock as a parameter.

    findIterable.forEach(printBlock);
    
    function iterateFunc(doc) {
       console.log(JSON.stringify(doc, null, 4));
    }
    
    function errorFunc(error) {
       console.log(error);
    }
    
    cursor.forEach(iterateFunc, errorFunc);
    

    In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:

    async for doc in cursor:
        print(doc)
    
    foreach (var doc in result) {
       Console.WriteLine(doc.ToJson());
    }
    
    5

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned. Note that the records have a height (“size.h”) of less than 15.

    { "_id" : ObjectId("5ae14d2e124da839884ff939"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93a"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93b"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93d"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    ../../_images/compass-find-nested-query-op.png
    {u'_id': ObjectId('5ada625baea65088bf0aa131'),
     u'item': u'journal',
     u'qty': 25,
     u'size': {u'h': 14, u'uom': u'cm', u'w': 21},
     u'status': u'A'}
    {u'_id': ObjectId('5ada625baea65088bf0aa132'),
     u'item': u'notebook',
     u'qty': 50,
     u'size': {u'h': 8.5, u'uom': u'in', u'w': 11},
     u'status': u'A'}
    {u'_id': ObjectId('5ada625baea65088bf0aa133'),
     u'item': u'paper',
     u'qty': 100,
     u'size': {u'h': 8.5, u'uom': u'in', u'w': 11},
     u'status': u'D'}
    {u'_id': ObjectId('5ada625baea65088bf0aa135'),
     u'item': u'postcard',
     u'qty': 45,
     u'size': {u'h': 10, u'uom': u'cm', u'w': 15.25},
     u'status': u'A'}
    

    Create a method to print the results of the iteration

    { "_id" : { "$oid" : "5ada88359b267e9b5bd393b9" }, "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393ba" }, "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393bb" }, "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393bd" }, "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    { _id: 5ade424c84c9ca2d56d31697,
      item: 'journal',
      qty: 25,
      size: { h: 14, w: 21, uom: 'cm' },
      status: 'A' }
    { _id: 5ade424c84c9ca2d56d31698,
      item: 'notebook',
      qty: 50,
      size: { h: 8.5, w: 11, uom: 'in' },
      status: 'A' }
    { _id: 5ade424c84c9ca2d56d31699,
      item: 'paper',
      qty: 100,
      size: { h: 8.5, w: 11, uom: 'in' },
      status: 'D' }
    { _id: 5ade424c84c9ca2d56d3169b,
      item: 'postcard',
      qty: 45,
      size: { h: 10, w: 15.25, uom: 'cm' },
      status: 'A' }
    
    {'_id': ObjectId('5adb5140aea650d18e402f17'),
     'item': 'journal',
     'qty': 25,
     'size': {'h': 14, 'uom': 'cm', 'w': 21},
     'status': 'A'}
    {'_id': ObjectId('5adb5140aea650d18e402f18'),
     'item': 'notebook',
     'qty': 50,
     'size': {'h': 8.5, 'uom': 'in', 'w': 11},
     'status': 'A'}
    {'_id': ObjectId('5adb5140aea650d18e402f19'),
     'item': 'paper',
     'qty': 100,
     'size': {'h': 8.5, 'uom': 'in', 'w': 11},
     'status': 'D'}
    {'_id': ObjectId('5adb5140aea650d18e402f1b'),
     'item': 'postcard',
     'qty': 45,
     'size': {'h': 10, 'uom': 'cm', 'w': 15.25},
     'status': 'A'}
    
    { "_id" : ObjectId("5ade261a9270d01f8c3d2750"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ade261a9270d01f8c3d2751"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : ObjectId("5ade261a9270d01f8c3d2752"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    { "_id" : ObjectId("5ade261a9270d01f8c3d2754"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    

    Read Data with Compound Queries

    Now you will read data from MongoDB using AND and OR logic to form compound queries.

    1

    Write an implied AND query.

    To write a compound query in MongoDB that matches all of the query predicates (i.e. a logical AND), specify all of the fields that you wish to match in your find document. By default, MongoDB matches all of the fields.

    The following example retrieves all documents in the inventory collection where the status equals "A" and qty is less than ($lt) 30:

    myCursor = db.inventory.find( { status: "A", qty: { $lt: 30 } } )
    

    Copy the following filter into the Compass query bar and click Find:

    { status: "A", qty: { $lt: 30 } }
    
    cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
    
    findIterable = collection.find(and(eq("status", "A"), lt("qty", 30)));
    
    var cursor = db.collection('inventory').find({ 
      status: "A", 
      qty: { $lt: 30 }
    });
    
    cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
    

    For completeness, this is how you might wrap this call and run it with the asyncio event loop.

    async def do_retrieve_implied_and():
       cursor = db.inventory.find({"status": "A", "qty": {"$lt": 30}})
       async for doc in cursor:
           pprint.pprint
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_implied_and())
    
    var builder = Builders<BsonDocument>.Filter;
    var filter = builder.And(builder.Eq("status", "A"), builder.Lt("qty", 30));
    var result = collection.Find(filter).ToList();
    

    MongoDB also provides a $and logical operator as part of its logical query operators, but the “implied AND” described above is a more common pattern.

    2

    Iterate over the results.

    This query does not require cursor iteration in mongo shell because the shell returns up to 20 results.

    You will see a list of all of the documents that match your criteria in the query window.

    from pprint import pprint
    
    for inventory in cursor:
         pprint(inventory)
    

    You can implement a com.mongodb.Block to print the results of the iteration

    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    

    Then iterate the cursor for documents, passing the printBlock as a parameter.

    findIterable.forEach(printBlock);
    
    function iterateFunc(doc) {
       console.log(JSON.stringify(doc, null, 4));
    }
    
    function errorFunc(error) {
       console.log(error);
    }
    
    cursor.forEach(iterateFunc, errorFunc);
    

    In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:

    async for doc in cursor:
        print(doc)
    
    foreach (var doc in result) {
       Console.WriteLine(doc.ToJson());
    }
    
    3

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned. Your results should look something like the JSON below. Note that the record below has a status of "A" and a qty less than 30 per the criteria in the compound query.

    { "_id" : ObjectId("5ae14d2e124da839884ff939"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    
    ../../_images/compass-find-filter-and.png
    {u'_id': ObjectId('5ada625baea65088bf0aa131'),
     u'item': u'journal',
     u'qty': 25,
     u'size': {u'h': 14, u'uom': u'cm', u'w': 21},
     u'status': u'A'}
    
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393b9" }, "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    
    { _id: 5ade424c84c9ca2d56d31697,
      item: 'journal',
      qty: 25,
      size: { h: 14, w: 21, uom: 'cm' },
      status: 'A' }
    
    {'_id': ObjectId('5adb5140aea650d18e402f17'),
     'item': 'journal',
     'qty': 25,
     'size': {'h': 14, 'uom': 'cm', 'w': 21},
     'status': 'A'}
    
    { "_id" : ObjectId("5ade26de3d3a851fcd9c95da"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    
    6

    Write an “or” query.

    Using the $or query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the $or query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the query operator, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    Using the Or filter method, specify a compound query that joins each clause with a logical OR conjunction so that the query selects the documents in the collection that match at least one condition.

    The following example retrieves all documents in the collection where the status equals "A" or qty is less than 30:

    myCursor = db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
    

    Copy the following filter into the Compass query bar and click Find:

    { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }
    
    cursor = db.inventory.find(
        {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
    
    findIterable = collection.find(or(eq("status", "A"), lt("qty", 30)));
    
    var cursor = db.collection('inventory').find({ 
      $or: [ {status: "A" }, { qty: { $lt: 30 } } ]
    });
    
    cursor = db.inventory.find(
        {"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
    

    For completeness, this is how you might wrap this call and run it with the asyncio event loop.

    async def do_retrieve_or():
        cursor = db.inventory.find({"$or": [{"status": "A"}, {"qty": {"$lt": 30}}]})
        async for doc in cursor:
            pprint.pprint(doc)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_or())
    
    var builder = Builders<BsonDocument>.Filter;
    var filter = builder.Or(builder.Eq("status", "A"), builder.Lt("qty", 30));
    var result = collection.Find(filter).ToList();
    
    7

    Iterate over rhe results.

    By default, the shell will only show the first 20 documents and return a cursor. This is adequate when the result set only contains a few documents.

    If your result set is larger, to see all of the results of your query, iterate the cursor.

    while (myCursor.hasNext()) {
        print(tojson(myCursor.next()));
    }
    

    Note

    You can also manually iterate through the results by typing it when prompted by the shell.

    You will see a list of all of the documents that match your criteria in the query window.

    from pprint import pprint
    
    for inventory in cursor:
         pprint(inventory)
    

    You can implement a com.mongodb.Block to print the results of the iteration

    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    

    Then iterate the cursor for documents, passing the printBlock as a parameter.

    findIterable.forEach(printBlock);
    
    function iterateFunc(doc) {
       console.log(JSON.stringify(doc, null, 4));
    }
    
    function errorFunc(error) {
       console.log(error);
    }
    
    cursor.forEach(iterateFunc, errorFunc);
    

    In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:

    async for doc in cursor:
        print(doc)
    
    foreach (var doc in result) {
       Console.WriteLine(doc.ToJson());
    }
    
    8

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned. Note that the record has a status of "A" but a qty of more than 30, which is acceptable according to the $or criteria.

    { "_id" : ObjectId("5ae14d2e124da839884ff939"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93a"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93d"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    ../../_images/compass-find-filter-or.png
    {'_id': ObjectId('5ae14d2e124da839884ff939'),
     'item': 'journal',
     'qty': 25,
     'size': {'h': 14, 'uom': 'cm', 'w': 21},
     'status': 'A'}
    {'_id': ObjectId('5ae14d2e124da839884ff93a'),
     'item': 'notebook',
     'qty': 50,
     'size': {'h': 8.5, 'uom': 'in', 'w': 11},
     'status': 'A'}
    {'_id': ObjectId('5ae14d2e124da839884ff93d'),
     'item': 'postcard',
     'qty': 45,
     'size': {'h': 10, 'uom': 'cm', 'w': 15.25},
     'status': 'A'}
    
    { "_id" : { "$oid" : "5ae39ecb124da8e9ed76c17f" }, "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : { "$oid" : "5ae39ecb124da8e9ed76c180" }, "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : { "$oid" : "5ae39ecb124da8e9ed76c183" }, "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    [ { _id: 5ae3a1a0fe333febb35af7b3,
        item: 'journal',
        qty: 25,
        size: { h: 14, w: 21, uom: 'cm' },
        status: 'A' },
      { _id: 5ae3a1a0fe333febb35af7b4,
        item: 'notebook',
        qty: 50,
        size: { h: 8.5, w: 11, uom: 'in' },
        status: 'A' },
      { _id: 5ae3a1a0fe333febb35af7b7,
        item: 'postcard',
        qty: 45,
        size: { h: 10, w: 15.25, uom: 'cm' },
        status: 'A' } ]
    
    {'_id': ObjectId('5ae14d2e124da839884ff939'),
     'item': 'journal',
     'qty': 25,
     'size': {'h': 14, 'uom': 'cm', 'w': 21},
     'status': 'A'}
     '_id': ObjectId('5ae14d2e124da839884ff93a'),
     'item': 'notebook',
     'qty': 50,
     'size': {'h': 8.5, 'uom': 'in', 'w': 11},
     'status': 'A'}
     '_id': ObjectId('5ae14d2e124da839884ff93d'),
     'item': 'postcard',
     'qty': 45,
     'size': {'h': 10, 'uom': 'cm', 'w': 15.25},
     'status': 'A'}
    
    { "_id" : ObjectId("5ae3a38356cd4decbfea7a29"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ae3a38356cd4decbfea7a2a"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : ObjectId("5ae3a38356cd4decbfea7a2d"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    

    Retrieving Data with More Than One Compounding Clause

    Now you will retrieve data from MongoDB using AND and OR logic together to form compound queries.

    1

    Write an implied AND query with an “or” clause.

    In the following example, the compound query document selects all documents in the collection where the status equals "A" and either qty is less than 30 or item starts with the character p:

    myCursor = db.inventory.find( {
         status: "A",
         $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
    } )
    

    Copy the following filter into the Compass query bar and click Find:

    { status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] }
    
    cursor = db.inventory.find({
        "status": "A",
        "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
    
    findIterable = collection.find(
            and(eq("status", "A"),
                    or(lt("qty", 30), regex("item", "^p")))
    );
    
    var cursor = db.collection('inventory').find({ 
      status: "A",
      $or: [ { qty: { $lt: 30 } }, { item: { $regex: "^p" } } ]
    });
    
    cursor = db.inventory.find({
        "status": "A",
        "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
    

    For completeness, this is how you might wrap this call and run it with the asyncio event loop.

    async def do_retrieve_regex():
        cursor = db.inventory.find({
               "status": "A",
               "$or": [{"qty": {"$lt": 30}}, {"item": {"$regex": "^p"}}]})
        async for doc in cursor:
            pprint.pprint(doc)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_regex())
    
    var builder = Builders<BsonDocument>.Filter;
    var filter = builder.And(
        builder.Eq("status", "A"),
        builder.Or(builder.Lt("qty", 30), builder.Regex("item", new BsonRegularExpression("^p"))));
    var result = collection.Find(filter).ToList();
    

    Note

    MongoDB supports regular expressions to perform string pattern matches.

    2

    Iterate over the results.

    This query does not require cursor iteration in mongo shell because the shell returns up to 20 results.

    You will see a list of all of the documents that match your criteria in the query window.

    from pprint import pprint
    
    for inventory in cursor:
         pprint(inventory)
    

    You can implement a com.mongodb.Block to print the results of the iteration

    Block<Document> printBlock = new Block<Document>() {
        @Override
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    

    Then iterate the cursor for documents, passing the printBlock as a parameter.

    findIterable.forEach(printBlock);
    
    function iterateFunc(doc) {
       console.log(JSON.stringify(doc, null, 4));
    }
    
    function errorFunc(error) {
       console.log(error);
    }
    
    cursor.forEach(iterateFunc, errorFunc);
    

    In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:

    async for doc in cursor:
        print(doc)
    
    foreach (var doc in result) {
       Console.WriteLine(doc.ToJson());
    }
    
    3

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned.

    { "_id" : ObjectId("5ae14d2e124da839884ff939"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ae14d2e124da839884ff93d"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    ../../_images/compass-find-filter-and-or.png
    {u'_id': ObjectId('5ada8c109b267e9d1ade9038'),
     u'item': u'journal',
     u'qty': 25,
     u'size': {u'h': 14, u'uom': u'cm', u'w': 21},
     u'status': u'A'}
    {u'_id': ObjectId('5ada8c109b267e9d1ade903c'),
     u'item': u'postcard',
     u'qty': 45,
     u'size': {u'h': 10, u'uom': u'cm', u'w': 15.25},
     u'status': u'A'}
    
    { "_id" : { "$oid" : "5ada8c109b267e9d1ade9038" }, "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : { "$oid" : "5ada8c109b267e9d1ade903c" }, "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    
    [ { _id: 5adedb5ffa97c643763556e8,
        item: 'journal',
        qty: 25,
        size: { h: 14, w: 21, uom: 'cm' },
        status: 'A' },
      { _id: 5adedb5ffa97c643763556ec,
        item: 'postcard',
        qty: 45,
        size: { h: 10, w: 15.25, uom: 'cm' },
        status: 'A' } ]
    
    {'_id': ObjectId('5ade276281031b2005294976'),
     'item': 'postcard',
     'qty': 45,
     'size': {'h': 10, 'uom': 'cm', 'w': 15.25},
     'status': 'A'}
    {'_id': ObjectId('5ade261a9270d01f8c3d2750'),
     'item': 'journal',
     'qty': 25,
     'size': {'h': 14, 'uom': 'cm', 'w': 21},
     'status': 'A'}
    
    { "_id" : ObjectId("5ade276281031b2005294972"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    { "_id" : ObjectId("5ade276281031b2005294976"), "item" : "postcard", "qty" : 45, "size" : { "h" : 10, "w" : 15.25, "uom" : "cm" }, "status" : "A" }
    

    When you are done working with your MongoDB data, close your connection to MongoDB:

    mongoClient.close();
    

    Summary

    Congratulations! If you have successfully completed this guide, you have read data from MongoDB using MongoDB query operators and compound queries.

    What’s Next

    In the next guide, you’ll learn how to update data in MongoDB.