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

CRUD using the shell

The mongo shell is equivalent to the administration console used by relational databases. Connecting to the mongo shell is as easy as typing the following:

$ mongo

Type it on the command line for standalone servers or replica sets. Inside the shell, we can view available databases simply by typing the following:

$ db

And connect to a database by typing the following:

> use <database_name>

The mongo shell can be used for querying and updating data in our databases. Finding documents from a collection named books is as easy as the following:

> db.books.find()
{ "_id" : ObjectId("592033f6141daf984112d07c"), "title" : "mastering mongoDB", "isbn" : "101" }

And inserting this document in the books collection can be done via the following:

> db.books.insert({title: 'mastering mongoDB', isbn: '101'})
WriteResult({ "nInserted" : 1 })

The result we get back from MongoDB informs us that the write succeeded and inserted one new document in the database.

Deleting this document has similar syntax and results:

> db.books.remove({isbn: '101'})
WriteResult({ "nRemoved" : 1 })

Try to update this same document:

> db.books.update({isbn:'101'}, {price: 30})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.books.find()
{ "_id" : ObjectId("592034c7141daf984112d07d"), "price" : 30 }

Here, we notice a couple of things:

  • First, the JSON-like formatted field in the update command is our query to search for documents to update.
  • The  WriteResult object notifies us that the query matched one document and notified one document.
  • Most importantly, the contents of this document were entirely replaced by the contents of the second JSON-like formatted field. We lost information on the title and ISBN!

By default, the update command in MongoDB will replace the contents of our document with the document we specify in the second argument. If we want to update the document and add new fields to it we need to use the $set operator like this:

> db.books.update({isbn:'101'}, {$set: {price: 30}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now our document matches what we would expect:

> db.books.find()
{ "_id" : ObjectId("592035f6141daf984112d07f"), "title" : "mastering mongoDB", "isbn" : "101", "price" : 30 }

However, deleting a document can be done in several ways, the most simple of which is by its unique ObjectId:

> db.books.remove("592035f6141daf984112d07f")
WriteResult({ "nRemoved" : 1 })
> db.books.find()
>

We can see here that when there are no results, the mongo shell will not return anything other than the shell prompt itself >.

主站蜘蛛池模板: 康马县| 双江| 嘉荫县| 潢川县| 全南县| 军事| 巴南区| 九江县| 和平县| 长岭县| 永靖县| 孟津县| 阿合奇县| 宜宾市| 舟山市| 静海县| 乌拉特前旗| 阿鲁科尔沁旗| 固安县| 普宁市| 会理县| 普定县| 吉木乃县| 陇川县| 浦城县| 姚安县| 虞城县| 丹凤县| 黔东| 宁武县| 长兴县| 民权县| 双鸭山市| 太湖县| 额济纳旗| 清河县| 乌兰县| 和硕县| 云和县| 定州市| 简阳市|