Constructing documents in MongoDB - Part 8
The whole purpose of setting up a Mongo database is so that you can store documents, so a really, really critical operation is to create and insert those documents. Fortunately, that all occurs in one single step. One single command both creates the document and inserts it.
Now the first thing we’d like to know is what are the current documents in this particular database? db.products.find() is the most basic find() command, and you’ll notice we have eleven products listed in this particular database, very simple. Now a few things I would like to point out. First of all, this ObjectId, that is not something that you’re going to insert. That is something MongoDB automatically generates for you. Next, MongoDB has multiple data types, really only a few. They have strings, they have integers, they have decimal numbers, and they have dates and times. As we go forward, we’ll introduce you to those as needed.
The output may look little awkward, but if you would like to see it in eye pleasing manner add pretty() command. db.products.find().pretty() will give you a decent json look.
Right now, let’s insert a new product using db.products.insert()
db.products.insert({name:”smartphone”,brand:”samsung”,type:”phone”,price:200})
Now again, I’d like to see that this product was entered, db.products.find(),and we can see it right there. Or the easiest way is to look at the count using db.products.find().count() before and after insertion.
Now the next thing I’d like to enter multiple records at one time, and that’s likely to happen pretty frequently. First let’s create an array variable, var myproducts, and because it’s an array, I have to open the square brackets, and inside it I simply insert as many products as I’d like.
var myproducts = [{name:”smartphone”,brand:”Acer”,type:”phone”,price:100}, {name:”laptop”,brand:”Apple”,type:”computer”,price:1200}]
Now we’re going to insert the variable, and that’s pretty easy, db.products.insert(myproducts). And it tells you, BulkWriteResult(), there were no errors, there were two inserted, everything’s good to go. So you can see that creating and inserting records is a pretty trivial task.