- Learning Node.js for Mobile Application Development
- Stefan Buttigieg Milorad Jevdjenic
- 877字
- 2021-07-09 21:21:33
Creating our collections
Now that we have created a database, let's populate it with some collections by performing the following steps:
- 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.
- 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 isOrderBase
. - The
createCollection('Products')
function is one of the many member methods ofdb
. Needless to say, it creates a new collection and adds it todb
. Its parameter, a string, is the name of the new collection.
- The
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.
- 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.
- 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 }
- 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 particularWriteResult
instance tells us that the write was successful (as no error was returned), and that we inserted a total of one new document. - 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 isOrderBase
. Products
is our products collection that belongs todb
.- 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.
- The
- 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
. - 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 ordinaryWriteResult
. 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
). - 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 }
- 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"} ])
- 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" }
- The Complete Rust Programming Reference Guide
- 微服務與事件驅動架構
- Mastering Entity Framework
- Web Development with Django Cookbook
- INSTANT Sencha Touch
- Python金融數據分析
- Magento 1.8 Development Cookbook
- 組態軟件技術與應用
- RabbitMQ Essentials
- RESTful Java Web Services(Second Edition)
- Swift 4 Protocol-Oriented Programming(Third Edition)
- JSP程序設計實例教程(第2版)
- Qt 5.12實戰
- Python面向對象編程(第4版)
- Go語言編程之旅:一起用Go做項目