官术网_书友最值得收藏!

Creating our collections

Now that we have created a database, let's populate it with some collections by performing the following steps:

  1. Run the following to create a collection for Products:
    > db.createCollection('Products')
    

    MongoDB will respond with the following:

    { "ok" : 1 }
    

    The preceding code indicates that the command was executed successfully. Note that the response is returned to us in the JSON format.

  2. Let's pause for a minute and break down the preceding command so that we understand what we just did:
    • The db is a JavaScript object that represents the currently selected database. In our case, it is OrderBase.
    • The createCollection('Products') function is one of the many member methods of db. Needless to say, it creates a new collection and adds it to db. Its parameter, a string, is the name of the new collection.

In other words, working with MongoDB is actually a matter of issuing commands in pure JavaScript. Not only that, but the data itself and the responses to the commands are encoded as JSON! It's obvious right away why MongoDB makes a perfect, seamless fit for JavaScript projects.

  1. Let's create two other collections as well to store our orders while we are at it:
    > db.createCollection('Orders')
    > db.createCollection(Customers'Customers')
    

    You will get the same ok responses as before.

  2. Now, let's add some products to our Product collection. In our case, let's say that a product has the following defining characteristics:
    • A name of the string type
    • A price of the float type

    We can represent this as a simple JSON object, as follows:

    {
      "name" : "Apple",
      "price" : 2.5
    }
  3. Inserting name and price into the Products collection is equally simple:
    > db.Products.insert({"name" : "Apple", "price" : 2.5})
    

    The response will be as follows:

    WriteResult({ "nInserted" : 1 })
    

    The preceding result contains a WriteResult object, giving details about the outcome of a write operation against the MongoDB instance. This particular WriteResult instance tells us that the write was successful (as no error was returned), and that we inserted a total of one new document.

  4. Again, let's take a closer look at the command that we just issued:
    • The db is still the database that we are operating on, which is OrderBase.
    • Products is our products collection that belongs to db.
    • The insert()method belongs to the products collection (note that even collections are represented as plain JavaScript objects with properties and methods). It takes a JSON object, such as the one that we defined in the preceding code, and inserts it into the collection as a new document.

    Now that one of our collections actually contains a document, we can ask MongoDB to tell us what is in it.

  5. Issue the following command:
    > db.Products.find()
    

    The find()method tells MongoDB to look up in the documents from the associated collection. If you pass no parameters to it (an empty find), it will return all the documents in the collection. Fortunately for us, we do not have enough documents (yet) to cause too much screen-scrolling from doing so:

    { "_id" : ObjectId("54f8f04a598e782be72d6294"),
     "name" : "Apple",
    "price" : 2.5 }

    This is the same apple that we inserted earlier...or is it? Note that MongoDB created an ObjectId instance for it and automatically added it to the objects members. This will always be done (unless you specify a manual _id), since all the documents in a MongoDB database are required to have their own unique _id.

    Note

    If you are running this example on your own machine, you will quickly note that the _id values for your objects will differ from the ones seen here since the IDs are randomly generated at the time of insertion.

  6. Let's go ahead and insert two more products. However, rather than executing one insert statement for each of them, we can instead perform a bulk insertion this time by passing all the objects that we want to insert in a JSON array, as follows:
    > db.Products.insert([{"name" : "Pear", "price" : 3.0}, {"name" : "Orange", "price" : 3.0}])
    

    The response will be as follows:

    BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
    })

    This response, a BulkWriteResult method, is clearly a lot more complex than an ordinary WriteResult. We do not need to concern ourselves with what its properties mean just yet. It is enough that we can read from it that two documents were written to the database ("nInserted" : 2).

  7. Let's issue another find() method to make sure that our database contains what we expect:
    { "_id" : ObjectId("54f8f04a598e782be72d6294"), "name" : "Apple", "price" : 2.5 }
    { "_id" : ObjectId("54f8f6b8598e782be72d6295"), "name" : "Pear", "price" : 3 }
    { "_id" : ObjectId("54f8f6b8598e782be72d6296"), "name" : "Orange", "price" : 3 }
    
  8. Now, let's wrap up by adding some customers as well. We will add our orders a bit later:
    > db.Customers.insert(
    [
    {"firstName" : "Jane", "lastName" : "Doley"},
    {"firstName" : "John", "lastName" : "Doley"}
    ])
    
  9. Finally, verify that we now have customers to work with by executing the following command:
    > db.Customers.find()
    

    The response will be as follows:

    {
    "_id" : ObjectId("54f94003ea8d3ea069f2f652"),
    "firstName" : "Jane",
    "lastName" : "Doley"
    },
    {
    "_id" : ObjectId("54f94003ea8d3ea069f2f653"),
    "firstName" : "John",
    "lastName" : "Doley"
    }
主站蜘蛛池模板: 阳朔县| 湘潭县| 临颍县| 庆安县| 拉孜县| 新民市| 利川市| 大方县| 林西县| 崇信县| 锡林郭勒盟| 山丹县| 乡宁县| 额济纳旗| 萍乡市| 蓬安县| 措勤县| 亚东县| 灵山县| 武冈市| 东莞市| 屯昌县| 靖安县| 桃江县| 银川市| 四川省| 金沙县| 休宁县| 怀柔区| 石河子市| 册亨县| 鹰潭市| 阳原县| 三穗县| 连云港市| 肃北| 象山县| 蒲江县| 东丽区| 维西| 宁阳县|