Read Data from MongoDB With Queries

Deployment Type:
Client:

    Author: MongoDB Documentation Team

    In the first Read Data from MongoDB guide, you retrieved a document from the inventory collection. In this guide, you will:

    • use the insertMany command to insert more documents into the collection
    • query the documents

    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

    Import Data and Query It

    In the first part of this guide, you will insert more documents and retrieve some of these documents from MongoDB using a simple query.

    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

    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

    Load more data into MongoDB.

    Tip

    If you have already imported data into your database using mongoimport, you can skip this step.

    Before you can write queries to extract data in a meaningful way, you’ll need to add more data to your database. You can do that by running the insertMany() nethod:

    db.inventory.insertMany( [
       { "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
       { "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
       { "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
       { "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
       { "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
    ]);
    
    [
        { "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
        { "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
        { "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
        { "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
        { "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
    ]
    

    For instructions on inserting documents in MongoDB Compass, see Insert Documents.

    # Subdocument key order matters in a few of these examples so we have
    # to use bson.son.SON instead of a Python dict.
    from bson.son import SON
    db.inventory.insert_many([
        {"item": "journal",
         "qty": 25,
         "size": SON([("h", 14), ("w", 21), ("uom", "cm")]),
         "status": "A"},
        {"item": "notebook",
         "qty": 50,
         "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
         "status": "A"},
        {"item": "paper",
         "qty": 100,
         "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
         "status": "D"},
        {"item": "planner",
         "qty": 75,
         "size": SON([("h", 22.85), ("w", 30), ("uom", "cm")]),
         "status": "D"},
        {"item": "postcard",
         "qty": 45,
         "size": SON([("h", 10), ("w", 15.25), ("uom", "cm")]),
         "status": "A"}])
    

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

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

    Now add the insertMany call.

    collection.insertMany(asList(
            Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
            Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
            Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
            Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
            Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
    ));
    
    db.collection('inventory').insertMany([
      { item: "journal",
        qty: 25,
        size: { h: 14, w: 21, uom: "cm" },
        status: "A"},
      { item: "notebook",
        qty: 50,
        size: { h: 8.5, w: 11, uom: "in" },
        status: "A"},
      { item: "paper",
        qty: 100,
        size: { h: 8.5, w: 11, uom: "in" },
        status: "D"},
      { item: "planner",
        qty: 75, size: { h: 22.85, w: 30, uom: "cm" },
        status: "D"},
      { item: "postcard",
        qty: 45,
        size: { h: 10, w: 15.25, uom: "cm" },
        status: "A"}
    ])
    .then(function(result) {
      // process result
    })
    
    # Subdocument key order matters in a few of these examples so we have
    # to use bson.son.SON instead of a Python dict.
    from bson.son import SON
    await db.inventory.insert_many([
        {"item": "journal",
         "qty": 25,
         "size": SON([("h", 14), ("w", 21), ("uom", "cm")]),
         "status": "A"},
        {"item": "notebook",
         "qty": 50,
         "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
         "status": "A"},
        {"item": "paper",
         "qty": 100,
         "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
         "status": "D"},
        {"item": "planner",
         "qty": 75,
         "size": SON([("h", 22.85), ("w", 30), ("uom", "cm")]),
         "status": "D"},
        {"item": "postcard",
         "qty": 45,
         "size": SON([("h", 10), ("w", 15.25), ("uom", "cm")]),
         "status": "A"}])
    

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

    async def do_insert_many():
        # Subdocument key order matters in a few of these examples so we have
        # to use bson.son.SON instead of a Python dict.
        from bson.son import SON
        await db.inventory.insert_many([
            {"item": "journal",
             "qty": 25,
             "size": SON([("h", 14), ("w", 21), ("uom", "cm")]),
             "status": "A"},
            {"item": "notebook",
             "qty": 50,
             "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
             "status": "A"},
            {"item": "paper",
             "qty": 100,
             "size": SON([("h", 8.5), ("w", 11), ("uom", "in")]),
             "status": "D"},
            {"item": "planner",
             "qty": 75,
             "size": SON([("h", 22.85), ("w", 30), ("uom", "cm")]),
             "status": "D"},
            {"item": "postcard",
             "qty": 45,
             "size": SON([("h", 10), ("w", 15.25), ("uom", "cm")]),
             "status": "A"}])
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_insert_many())
    

    First you will need to initialize the collection.

    var collection = database.GetCollection<BsonDocument>("inventory");
    

    Next create the array of BsonDocuments and pass it to the insertMany call on collection.

    var documents = new[]
    {
        new BsonDocument
        {
            { "item", "journal" },
            { "qty", 25 },
            { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } },
            { "status", "A" }
        },
        new BsonDocument
        {
            { "item", "notebook" },
            { "qty", 50 },
            { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
            { "status", "A" }
        },
        new BsonDocument
        {
            { "item", "paper" },
            { "qty", 100 },
            { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } },
            { "status", "D" }
        },
        new BsonDocument
        {
            { "item", "planner" },
            { "qty", 75 },
            { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } },
            { "status", "D" }
        },
        new BsonDocument
        {
            { "item", "postcard" },
            { "qty", 45 },
            { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } },
            { "status", "A" } },
    };
    collection.InsertMany(documents);
    
    4

    Retrieve specific documents in a collection.

    You can retrieve specific documents from a collection by applying filter criteria.

    To specify filter criteria, pass a JSON document containing the criteria you are searching for to the find method.

    The following example illustrate using a status of “D” as criteria for narrowing a find on a collection.

    myCursor = db.inventory.find( { status: "D" } )
    

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

    { status: "D" }
    
    cursor = db.inventory.find({"status": "D"})
    
    findIterable = collection.find(eq("status", "D"));
    
    var cursor = db.collection('inventory').find({ status: "D" });
    
    cursor = db.inventory.find({"status": "D"})
    

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

    async def do_retrieve_status():
        cursor = db.inventory.find({"status": "D"})
        async for doc in cursor:
            åpprint.pprint(doc)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_status())
    
    var filter = Builders<BsonDocument>.Filter.Eq("status", "D");
    var result = collection.Find(filter).ToList();
    
    5

    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());
    }
    
    6

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned. Note that all records return have a status of “D”.

    Note

    Your ObjectId values will differ from those shown.

    {
     item: "paper",
     qty: 100,
     size: {
       h: 8.5,
       w: 11,
       uom: "in"
       },
     status: "D"
    },
    {
     item: "planner",
     qty: 75,
     size: {
       h: 22.85,
       w: 30,
       uom: "cm"
       },
     status: "D"
    }
    
    ../../_images/compass-find-filter-inventory.png
    {u'_id': ObjectId('5ada8c109b267e9d1ade903a'),
     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('5ada8c109b267e9d1ade903b'),
     u'item': u'planner',
     u'qty': 75,
     u'size': {u'h': 22.85, u'uom': u'cm', u'w': 30},
     u'status': u'D'}
    
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393bb" }, "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    { "_id" : { "$oid" : "5ada88359b267e9b5bd393bc" }, "item" : "planner", "qty" : 75, "size" : { "h" : 22.85, "w" : 30, "uom" : "cm" }, "status" : "D" }
    
    { _id: 5ade424c84c9ca2d56d31699,
      item: 'paper',
      qty: 100,
      size: { h: 8.5, w: 11, uom: 'in' },
      status: 'D' }
    { _id: 5ade424c84c9ca2d56d3169a,
      item: 'planner',
      qty: 75,
      size: { h: 22.85, w: 30, uom: 'cm' },
      status: 'D' }
    
    {'_id': ObjectId('5adb5140aea650d18e402f19'),
     'item': 'paper',
     'qty': 100,
     'size': {'h': 8.5, 'uom': 'in', 'w': 11},
     'status': 'D'}
    {'_id': ObjectId('5adb5140aea650d18e402f1a'),
     'item': 'planner',
     'qty': 75,
     'size': {'h': 22.85, 'uom': 'cm', 'w': 30},
     'status': 'D'}
    
    { "_id" : ObjectId("5ade239b5923f61e2db8541e"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    { "_id" : ObjectId("5ade239b5923f61e2db8541f"), "item" : "planner", "qty" : 75, "size" : { "h" : 22.850000000000001, "w" : 30, "uom" : "cm" }, "status" : "D" }
    

    Query Data Using Embedded Documents as Criteria

    Now that you have an understanding of how to retrieve data using query documents, you will now query against embedded documents.

    1

    Retrieve specific documents in a collection based on the contents of an embedded document.

    If you wish to select documents that match all of the fields in an embedded JSON object, specify an exact match of the embedded document, including all of the fields and values in that embedded document in the order in which they appear in the collection.

    For example, the following query selects all documents where the size field equals the document { "h" : 14, "w" : 21, "uom" : "cm"}:

    myCursor = db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
    

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

    { size: { h: 14, w: 21, uom: "cm" } }
    
    cursor = db.inventory.find(
        {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
    

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

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

    Now add the query.

    FindIterable<Document> findIterable = collection.find(eq("size", Document.parse("{ h: 14, w: 21, uom: 'cm' }")));
    
    var cursor = db.collection('inventory').find({ 
      size: { h: 14, w: 21, uom: "cm" }
    });
    
    cursor = db.inventory.find(
        {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
    

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

    async def do_retrieve_embedded():
        cursor = db.inventory.find(
        {"size": SON([("h", 14), ("w", 21), ("uom", "cm")])})
        async for doc in cursor:
            pprint.pprint(doc)
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_embedded())
    
    var filter = Builders<BsonDocument>.Filter.Eq("size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } });
    var result = collection.Find(filter).ToList();
    
    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. Note that the record matches the selection criteria exactly.

    Note

    Your ObjectId values will differ from those shown.

    { "_id" : ObjectId("5ae14d2e124da839884ff939"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }
    
    ../../_images/compass-match-embedded.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("5ade248f6847901ef531c3ff"), "item" : "journal", "qty" : 25, "size" : { "h" : 14, "w" : 21, "uom" : "cm" }, "status" : "A" }å
    

    Query Data Using Embedded Documents With Dot Notation

    Now you will explore how to query embedded documents using dot notation.

    1

    Retrieve specific documents in a collection with dot notation.

    If you wish to select documents that exactly match just one of the fields in an embedded JSON object, use dot notation. ("field.nestedField").

    When querying using dot notation., the field and nested field names must be inside quotation marks.

    The following example selects all documents where the field uom nested in the size field equals "in":

    myCursor = db.inventory.find( { "size.uom": "in" } )
    

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

    { "size.uom": "in" }
    
    cursor = db.inventory.find({"size.uom": "in"})
    

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

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

    Now add the query.

    findIterable = collection.find(eq("size.uom", "in"));
    
    var cursor = db.collection('inventory').find({ 
      "size.uom": "in"
    });
    
    cursor = db.inventory.find({"size.uom": "in"})
    

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

    async def do_retrieve_embedded_dot():
        cursor = db.inventory.find({"size.uom": "in"})
        async for doc in cursor:
            pprint.pprint(doc)
    
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_retrieve_embedded_dot())
    
    var filter = Builders<BsonDocument>.Filter.Eq("size.uom", "in");
    var result = collection.Find(filter).ToList();
    
    2

    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());
    }
    
    4

    Check your results.

    If you have loaded data into your test database, you will see one or more JSON documents returned. Note that the result record has a uom of in.

    Note

    Your ObjectId values will differ from those shown.

    { "_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" }
    
    ../../_images/compass-find-nested-field.png
    {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'}
    

    Create a method to print the results of the iteration

    { "_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: 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': 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("5ade2538321fd31f43ea1f56"), "item" : "notebook", "qty" : 50, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "A" }
    { "_id" : ObjectId("5ade2538321fd31f43ea1f57"), "item" : "paper", "qty" : 100, "size" : { "h" : 8.5, "w" : 11, "uom" : "in" }, "status" : "D" }
    

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

    mongoClient.close();
    

    Summary

    If you have successfully completed this guide, you have retrieved data from MongoDB using specific criteria as expressed in MongoDB’s query syntax. You have also used the embedded document query syntax to retrieve documents based on embedded fields.

    What’s Next

    In the next guide, you’ll learn how to read data from MongoDB using operators and compound queries.