MongoDB Series Two

Source: Internet
Author: User
Tags array length modifier mongodb windows

Brief introduction

MongoDB is a database based on distributed file storage. Written by the C + + language. Designed to provide scalable, high-performance data storage solutions for Web applications.

MongoDB is a high-performance, open-source, modeless document-based database that is a popular one in the current NoSQL database.

MongoDB is a product between a relational database and a non-relational database, and is the most versatile and most like relational database in a non-relational database. The data structure he supports is very loose and is a JSON-like Bjson format, so you can store more complex data types. MONGO's biggest feature is that the query language he supports is very powerful, and its syntax is a bit like an object-oriented query language that almost implements most of the functionality of a relational database single-table query, and also supports indexing of data.

The traditional relational database is usually composed of three hierarchical concepts of database, table, record, and MongoDB is made up of database, collection (collection), Three levels of document objects. MongoDB is for tables in relational databases, but there is no concept of columns, rows, and relationships in the collection, which embodies the nature of pattern freedom.

Characteristics

  It is characterized by high performance, easy to deploy, easy to use, and easy to store data. The main features are:

1) for collection storage, easy to store the object type of data.

2) Mode freedom.

3) Support dynamic query.

4) full index support, including internal objects.

5) Support query.

6) Support replication and recovery.

7) Use efficient binary data storage, including large objects (such as video, etc.).

8) automatically handles fragmentation to support scalability at the cloud level.

9) support multiple languages such as ruby,python,java,c++,php,c#.

10) The file storage format is Bson (a JSON extension).

11) can be accessed via the network.

Each file function

The Mongod.exe is used to connect to the MONGO database server, which is the server side.

Mongo.exe is used to start the MongoDB shell, which is the client.

Mongodump Logical Backup tool.

Mongorestore Logical Recovery Tool.

Mongoexport Data Export tool.

Mongoimport Data Import Tool.

Installing MongoDB
Mongod--dbpath D:\MongoDB\data--logpath=d:\mongodb\logs\mongodb.log--logappend

MongoDB Windows Environment Installation and configuration This article describes the Windows installation of MongoDB good

MongoDB DLL drivers used in C #

MongoDB.Driver.dll: As the name implies, the driver

MongoDB.Bson.dll: serialization, JSON-related

Http://files.cnblogs.com/files/liyunhua/MongoDBDll.zip

Most commonly used commands
// The use command is used to toggle the current database, and if the database does not exist, a new one is created first.  //  Show all databases / / Display all collections under the current database //  Delete collection If the delete succeeds returns "true", Otherwise return "false"db.dropdatabase ()// Delete current database

Simply say add, modify, delete

Db.users.insert ({' name ': ' Angela ', ' sex ': ' Feman '})//  This command inserts a piece of data into the Users collection. If the collection users do not exist, a new one is created before the data is inserted, and the parameters are passed in JSON format. db.users.update ({' name ': ' Xiangshu '},{' $set ': {' sex ': ' Women '}},upsert=true, multi=false) // explain a few parameters: first: The condition of the query, the second: the updated field, and the third: insert fourth if not present: whether to allow the modification of multiple records DB. Users.remove ({' name ': ' Xumingxiang '})// Delete record  If no parameters are passed inside the Remove method, all data  in the collection will be erased, But does not delete the collection itself and the associated index // lookup

The above Update method, above update the third parameter is Upsert,upsert operation is said: If I did not find, I am in the database add a, in fact, this also has the benefit, is to avoid I in the database inside the judge is update or add operation, It's easy to use.

By default the Update method is the overall update, and if you need a partial update, MongoDB has provided us with two modifiers: $inc and $set.

$inc modifier is also the abbreviation for increase,

Each modification will increment the value specified by $inc on the original basis,$inc modifier adds one to the age key of the document that matches the criteria, and by default only updates the first qualifying document. You can specify that all eligible documents be updated by the last parameter of the update function

$set Modify the contents of the matching document directly, if the modified key exists, it is modified directly, otherwise it is added. $unset Modifying the functionality that conforms to $set is the exact opposite

Operation of specific complex points see MONGO learning notes Data manipulation

Detailing the Find command

The FindOne method in the above example is to query the first statement.

General query conditions are and, or, in, not in, not

Db.person.find ({"Name": "Jack", "Age":)// equivalent to query Name= "Jack" and Age=25
Db.person.find ({$or: [{"Name": "Jack", "Age":]})// equivalent to query name= "Jack" or age=25
Db.person.find ({"name": {$in: ["Jack", "Joe"]}})// = query name in ("Jack", "Joe")

Unlike SQL Server, the data in the MongoDB in list can be of different types.

Db.person.find ({"name": {$nin: ["Jack", "Joe"]}})// = query name not IN ("Jack", "Joe")
Db.person.find ({"$or": [{"name": {"$in": ["Jack", "Joe"]}}, {"Age": +}]})// How to Mix $or and $in. 
Db.person.find ({"name": {"$not": {"$in": ["Jack", "Joe"]}})//$not represents inverse, equivalent to not in SQL. 

The following is a query related ...

Db.person.find ({}, {"Name": 1})// Returns the specified document key-value pair. Just returns the key-value pair for name. 
Db.person.find ({}, {"name": 0})// Specifies a document key-value pair that is not returned. Returns all key-value pairs except name. 

Well, if you need to query for some particular condition, you can actually use regular, look at the example below.

Db.person.find ({"Name":/^j/, "name":/e$/}); // Query name Startwith ' J ' and Endwith ' E '

Some queries are complicated, $where comes in handy.

function return this. Name = = ' Jack '; }})// query name= ' Jack '

Let's talk about the comparison operator.

$LT/$lte/$GT/$gte/$ne, which in turn is equivalent to </<=/>/>=/!=. (l means less g means greater e means equal n means not)

Db.person.find ({"Age": {"$gte": "#lte": 40}}); // return to qualifying age >= && age <=

Db.person.find ({"name": {"$ne": "Jack"}})// return condition matches name! = "Jack"

I believe that people often encounter null when querying data, the following is the null data type of query bar

Db.person.find ({"name":null})// when a query with null data is made, all values are null, and documents that do not contain the specified key are retrieved. Db.person.find ({"name": {"$in": [null], "$exists":True}})//  You need to judge the equality of NULL as an element in the array, even if there is only one element in the array. Then there is the $exists to determine whether the specified key exists. 

MongoDB and SQL Server data query is still a very different part of the most significant difference is the MONGODB array data query.

Specifically, let's say it. Now suppose the data in our database looks like this:

All documents containing banana in the Db.test.find ({"Fruit": "Banana"})// array will be retrieved. 
Db.test.find ({"Fruit": {"$all": ["banana", "Apple"}})// Retrieves the case where multiple elements are required in the array, using $all. The array must contain both apple and banana, but their order does not matter. 
Db.test.find ({"Fruit": ["apple", "banana", "Peach"]})// exact match, i.e. the retrieved document, the array data in the fruit value must exactly match the query criteria, i.e. not many, And the order must be kept consistent. 
Db.test.find ({"fruit.2": "Peach"})// matches the value of the subscript element specified in the array. The starting subscript for an array is 0. View the value of the second element in the fruit array as peach
Db.test.find ({"fruit": {$size: 3}})// can get the length of the array through $size, but $size cannot be used in conjunction with comparison operators. That is, the query fruit length of 3 ...

The above example is the query fruit array length of 3, if you need to query the length of more than 3 what should be done?

Db.test.update ({}, {"$set": {"Size": 3}},false,true)// can only be added with an additional key to represent the element data in the data, When you manipulate elements in your data, you need to update the value of the size key at the same time. test.update ({},{"$push": {"fruit": "Strawberry"}, "$inc": {"size": 1}},false,true)//  $inc Each time you add a new element, you have to atomically increment the size one time. Db.test.find ({},{"fruit": {"$slice": 2}, "Size": 0})// returns part of the data in the array via $slice. "$slice": 2 represents the first two elements in the array. "$slice":-2 represents the second two elements in the array. $slice: [2,1], which indicates that 1 is taken from the second 2 element, and all subsequent data is taken if the number of elements following the quantity greater than 2 is obtained. 

As you know, MongoDB is made up of three levels of database, collection (collection), Document object. When a Document object contains more than one document object, how should it be queried?

This is where $elemmatch comes in.

Suppose the data in our database is as shown

Db.person.find ({"Comments": {"$elemMatch": {"author": "Joe", "score": {"$gte": 3}}}

MongoDB Series Two

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.