Common commands for creating, updating, and deleting MongoDb documents

Source: Internet
Author: User

Common commands for creating, updating, and deleting MongoDb documents
Mongodb is written by C ++. Its name comes from the middle part of the word humongous. From its name, we can see that its ambition lies in the processing of massive data. The simplest description of this database is scalable, high-performance, open source, schema-free, and document-oriented database. MongoDB's main goal is to build a bridge between key/value storage (providing high performance and high scalability) and traditional RDBMS systems (rich functions, combines the advantages of both. Install and use: first install MongoDB on Ubuntu. Download MongoDB, the latest production version 1.7.0 1. decompress the file. $ tar-xvf mongodb-linux-i686-1.4.3.tgz 2. create a data directory for MongoDB, by default, it stores data in/data/db $ sudo mkdir-p/data/db/$ sudo chown 'id-U'/data/db 3. start the MongoDB service. $ mongodb-linux-i686-1.4.3/bin $. /mongod 4. open another terminal and make sure that you are in the bin directory of MongoDB and enter the following command. $. /mongo concepts a mongod service can create multiple databases. Each database can have multiple tables. The table here is called collection, and each collection can store multiple documents ), each document is stored in the hard disk in the form of BSON (binary json). Therefore, you can To store complex data types. It is stored in a single document. You can add or delete fields for one or more documents without affecting other documents. This is called schema-free, this is also the main advantage of document-based databases. Unlike the general key-value database, its value stores structure information, so you can perform read/write, statistics, and other operations on certain domains like relational databases. The biggest feature of Mongo is that it supports a very powerful query language. Its syntax is somewhat similar to an Object-Oriented Query Language. It can almost implement most of the functions similar to single-table queries in relational databases, it also supports data indexing. Mongo can also solve the query efficiency of massive data. According to official documents, when the data volume exceeds 50 GB, the Mongo database access speed is more than 10 times that of mysql. BSON is short for Binary JSON and is the Binary encoding format of a JSON Document Object. Like JSON, BSON allows you to insert document objects and arrays to other document objects and arrays, while extending the JSON data type. For example, BSON has the Date and BinDate types. BSON is compared to a binary exchange format, just like Protocol Buffers, but BSON is more "schema-less" than it, which is very flexible but takes a little larger space. BSON has the following three features: 1. Lightweight 2. cross-platform 3. Efficient namespace MongoDB stores BSON objects to collections. This series of database names and collection names are called a namespace. For example, java. util. List; is used to manage data in the database. Index mongodb can create an index for a field, which can be a combination index, a unique index, or an index that can be deleted. By default, each table has a unique index: _ id. If _ id is not specified during data insertion, the service automatically generates a _ id. to make full use of existing indexes, reduce the space overhead. It is best to specify the key of a unique as _ id. It is usually appropriate to use the Object ID, such as the product ID. Shell database operation: 1. super User related: 1. # enter the database admin use admin 2. # Add or modify the User Password db. addUser ('name', 'pwd') 3. # view the user list db. system. users. find () 4. # user authentication db. auth ('name', 'pwd') 5. # delete a user database. removeUser ('name') 6. # view all user show users 7. # view all databases. # view all collections show collections 9. # view the status of each collection database. printCollectionStats () 10. # view master-slave replication status db. printReplicationInfo () 11. # Fix the database. repairDatabase () 12. # Set the record profiling, 0 = off 1 = slow 2 = all db. setProfilingLevel (1) 13. # view profiling show profile 14. # copy the database. copyDatabase ('mail _ addr ', 'mail _ addr_tmp') 15. # Delete collection db. mail_addr.drop () 16. # Delete the current database. dropDatabase () 2. add, delete, and modify 1. # store nested object db. foo. save ({'name': 'xy', 'address': {'city': 'beijinging', 'post': 100096}, 'phone': [138,139]}) 2. # store the array object db. user_addr.save ({'uid': 'yushunzhi @ sohu.com ', 'al': ['test-1@sohu.com', 'test-2 @ sohu. Com ']}) 3. # modify according to query conditions. If the query condition does not exist, insert multiple records into the database. foo. update ({'yy': 5}, {'$ set': {'xx': 2 }}, upsert = true, multi = true) 4. # Delete the record db of yy = 5. foo. remove ({'yy': 5}) 5. # delete all record databases. foo. remove () 3. index 1. # Add an index: 1 (ascending),-1 (descending) 2. db. foo. ensureIndex ({firstname: 1, lastname: 1}, {unique: true}); 3. # index sub-objects 4. db. user_addr.ensureIndex ({'al. em ': 1}) 5. # viewing index information 6. db. foo. getIndexes () 7. db. foo. getIndexKeys () 8. # Delete An index 9. db. user_addr.dropIndex ('al. em_1 ') 4. query 1. # search for all 2. db. foo. find () 3. # search for a record 4. db. foo. findOne () 5. # retrieve 10 records based on conditions. 6. db. foo. find ({'msg ': 'Hello 1 '}). limit (10) 7. # sort sorting 8. db. deliver_status.find ({'from': 'ixigua @ sina.com '}). sort ({'dt',-1}) 9. db. deliver_status.find (). sort ({'ct ':-1 }). limit (1) 10. # count operation 11. db. user_addr.count () 12. # perform the distinct operation to query the specified column and repeat it 13. db. foo. distinct ('msg ') 14. # "> =" Operation 15. db. foo. find ({"timestamp": {"$ gte": 2}) 16. # search for sub-objects 17. db. foo. find ({'address. city ': 'beijing'}) 5. management 1. # view the size of collection data 2. db. deliver_status.dataSize () 3. # view colleciont status 4. db. deliver_status.stats () 5. # query the size of all indexes. 6. db. deliver_status.totalIndexSize () 5. advanced queries: advanced query condition operator $ gt: >$ lt: <$ gte: >=$ lte: <=$ ne :! =, <> $ In: in $ nin: not in $ all: all $ not: Anti-match (version 1.3.3 and later) query the database with name <> "bruce" and age> = 18. users. find ({name: {$ ne: "bruce"}, age: {$ gte: 18 }}); query the data db of creation_date> '2014-01-01 'and creation_date <= '2014-12-31. users. find ({creation_date: {$ gt: new Date (, 1), $ lte: new Date (, 31)}); query age in) data db. users. find ({age :{$ in: [20, 22, 24, 26]}); query the data db where age mod 10 is equal to 0. users. find ('this. age % 10 = 0 '); or db. users. find ({age :{$ mod: [10, 0]}); match all databases. users. find ({favorite_number: {$ all: [6, 8]}); you can query {name: 'David ', age: 26, favorite_number: [6, 8, 9]} {name: 'David ', age: 26, favorite_number: [6, 7, 9]} does not match the db where name = B * leads. users. find ({name: {$ not:/^ B. */}); query the data db whose age modulo value is 10 and not equal to 0. users. find ({age :{$ not :{$ mod: [10, 0] }}); # Return the age and _ id fields (_ id fields will always be returned) db for some returned fields. users. find ({}, {age: 1}); db. users. find ({}, {age: 3}); db. users. find ({}, {age: true}); db. users. find ({name: "bruce"}, {age: 1}); 0 is false, if not 0 is true, the returned age, address, and _ id fields db are returned. users. find ({name: "bruce"}, {age: 1, address: 1}); Exclude the returned age, address, and _ id fields db. users. find ({}, {age: 0, address: false}); db. users. find ({name: "bruce"}, {age: 0, address: false}); determine the number of array elements for {name: 'David ', age: 26, favorite_number: [6, 7, 9]} records matching db. users. find ({favorite_number: {$ size: 3}); does not match db. users. find ({favorite_number: {$ size: 2}); $ exists checks whether the field exists and queries all records with name fields. users. find ({name :{$ exists: true}); query all records that do not have the phone field. users. find ({phone: {$ exists: false}); $ type determines the field type query all name fields are character type db. users. find ({name: {$ type: 2}); query all the databases whose age fields are integer. users. find ({age: {$ type: 16}); For character fields, you can use a regular expression to query all the records that take the lead of letters B or B. users. find ({name:/^ B. */I}); $ elemMatch (1.3.1 or a later version) is the record matching an element of Javascript query and $ where query age> 18 in the array field, the following queries are all the same db. users. find ({age :{$ gt: 18}); db. users. find ({$ where: "this. age> 18 "}); db. users. find ("this. age> 18 "); f = function () {return this. age> 18} db. users. find (f); sort () by age ascending asc db. users. find (). sort ({age: 1}); desc db in descending order of age. users. find (). sort ({age:-1}); limit the number of returned records. limit () returns five db records. users. find (). limit (5); 3 records are returned and the information db is printed. users. find (). limit (3 ). forEach (function (user) {print ('My age is '+ user. age)}); the result is my age is 18 my age is 19 my age is 20. the start point of the returned record is skip () starting from 3rd records, returns 5 Records (limit 3, 5) db. users. find (). skip (3 ). limit (5); query the number of records count () db. users. find (). count (); db. users. find ({age: 18 }). count (); The following does not return 5, but the number of all records in the user table db. users. find (). skip (10 ). limit (5 ). count (); if you want to return the number of records after the limit, use count (true) or count (not 0) db. users. find (). skip (10 ). limit (5 ). count (true); group () assume that the test table only contains the following data:

{ domain: "www.mongodb.org"  , invoked_at: {d:"2009-11-03", t:"17:14:05"}  , response_time: 0.05  , http_action: "GET /display/DOCS/Aggregation"  }  

 

Count: count (*), total_time: sum (response_time), avg_time: total_time/count;
 db.test.group(  { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}  , key: {http_action: true}  , initial: {count: 0, total_time:0}  , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }  , finalize: function(out){ out.avg_time = out.total_time / out.count }  } );  [  {  "http_action" : "GET /display/DOCS/Aggregation",  "count" : 1,  "total_time" : 0.05,  "avg_time" : 0.05  }  ]

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.