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

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"
    }
主站蜘蛛池模板: 司法| 肥乡县| 金堂县| 巴彦淖尔市| 广水市| 曲周县| 万载县| 正蓝旗| 贞丰县| 杂多县| 夏邑县| 五华县| 钟祥市| 台安县| 巴林右旗| 卓尼县| 普宁市| 西平县| 宝丰县| 阿拉善左旗| 定州市| 广安市| 霍山县| 肃宁县| 马尔康县| 鄄城县| 阜平县| 民权县| 新闻| 张家界市| 庄河市| 宜州市| 九龙城区| 织金县| 刚察县| 永胜县| 东乌珠穆沁旗| 泰来县| 平果县| 万荣县| 太湖县|