MongoDB Common Data manipulation

Source: Internet
Author: User
Tags bulk insert emit mongodb server prev

1. Shell operations

MongoDB default connection is the test database, input db, you can see the current database is test, followed by common database operations

???? MongoDB storage is stored as a document, with various operations in JSON format

???????? Can be understood as. A collection of MongoDB is a table of relational databases that can contain various types of data, including collections.

?

???? Show databases: Displays the database and the space occupied by the database. shorthand for show DBS;

???? Use [dbname]: Select Database

???? Show Collections: Collection of current databases (table)

?

???? To close the MongoDB server side via the connection end

???? Use admin;

???? Db.shutdownserver ();

????

2. Data manipulation

???? The key for a numeric type in MongoDB is also stored as a string, while value distinguishes between numbers and strings. For example: The key value pair {"1": 23} and {1:23} are the same, {1:23} and {1: "23"} are different

?

???? Data manipulation takes: Database. Set. command (); The data inside is in the form of JSON extension (Bson).

?

???? add: Insert; No BULK INSERT, you can write a for loop in your code

???????? After inserting the data, the system adds a field "_id" by default, guaranteeing the uniqueness of the data.

???????? Db.user.insert ({name: "Lilei", Age: "30"});

???????? Db.user.insert ({name: "Hanmeimei", Age: "28"});

????

???? search: Find;

???????? The shell side of MongoDB is a JS syntax editor, which is fully compatible with JS syntax MongoDB.

???????? Support for exact query (=), Regular expression fuzzy query (/^.....$/), matching query (>=, <, <=,! =; Or,in,notin)

???????? 1. Exact query do not need to say , through the document to match the data, the same query out

???????? 2. Regular expression : JS regular expression, gray is often powerful.

???????? 3. Matching query: MongoDB for > or < is not recognized, to use the escape character

;

>=

<

<=

! =

$gt

$gte

$lt

$lte

$ne

????????????

or

in

notin

$or

$in

$nin

?

???????? Db.user.find (); Query all

???????? Db.user.find ({name: "Lilei"});//exact query

???????? Db.user.find ({name:/^jim/}); //Regular expression

???????? //Match query, note the wording!!!

???????? Db.user.find ({age:{$gt: 20}});

???????? Db.user.find ({age:{$gte: 28}});

???????? Db.user.find ({age:{$lt: 28}});

???????? Db.user.find ({age:{$lte: 28}});

???????? Db.user.find ({age:{$ne: 28}});

?

???????? Db.user.find ({name:/^j/,age:{$in: [14,16]}});

???????? Db.user.find ({name:/^j/,age:{$nin: [14,16]}});

???????? Db.user.find ({$or: [{name:/^j/},{name: "Lily"}]});

???? change:???? Update;

???????? MongoDB's update is divided into three categories: full-volume update, Partial update, batch update

???????? Update ({match fragment},{updated fragment},upsert, whether batch);

?

???????? 1. Full-scale update

???????????? Db.user.update ({name: "Lily"},{name: "Lily", age:27});???? //will update the first fragment of the match name= "Lily" to the following

????????

???????? 2. Partial Updates

???????????? For example, I want to update the age of the fragment {name: "Lily", age:30} to 20, in the way above, the second parameter needs to write the whole amount, which is obviously unrealistic.

???????????? $set, set the updated field directly; $inc, update incrementally on the update field.

???????????? Db.user.update ({name: "Jime"},{$set: {age:32}});???? //Set age=32

???????????? Db.user.update ({name:/^jim/},{$inc: {age:1}});???? //On the original age +1

????????

???????? 3. Batch update

???????????? Third parameter: Upsert (TRUE or FALSE)

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 me in the database inside the judge is update or add operation, use it very simple to update the third parameter set to True.

????????

In MongoDB if you match more than one, the default is to update only the first one, then if we have a need to batch update, then the implementation in MongoDB is also very simple, in the fourth parameter of the update is set to True.

???????????? Db.user.update ({name:/^jim/},{$inc: {age:1}},true,true);

???? Delete: Remove

???????? Db.user.remove (); Delete all

???????? Db.user.remove ({name: "Lily"});???? Delete Match

?

3. Aggregation functions

???? Count???? Count

???????? Db.user.count ();//All

???????? Db.user.count ({name: "Jim"});???? Meet the criteria

????

???? Distinct???? Go heavy

???????? Db.user.distinct ("age");???? Pay attention to the quotation marks.

????

???? Group???? Group

???????? This function is somewhat complex, and the group operation essentially forms a "k-v" model, in which the group operation is performed according to age, and value is the name corresponding to age. Here's a look at these parameters:

????? Key:? This is the group key, we are here for the age group.

???? initial: Each group shares an "initialization function", paying special attention to: Each group, such as the age=20 value of the list share a initial function, AGE=22 also share a initial function.

???? $reduce: The first parameter of this function is the current document object, the second parameter is the cumulative object of the last function operation, the first is {"Perosn" in initial: []}. How many documents are there, and how many times $reduce will be called.

???? Understanding: In fact, the group function will query the document according to the field specified by key, and the queried data is placed in the accumulated object by the function specified by reduce, which is an array of the accumulated objects (the initialized object is the initial specified). In this way, the key and the queried data are grouped together by the group function to achieve the purpose of grouping.

???? Invocation Example:

???????? Db.user.group ({

Key:{age:true},

Initial:{name:[]},

$reduce: Function (Cur,prev) {

???? Prev.name.push (Cur.name);

}

});

????????

This way we see the name of the person through age, but sometimes we may have the following requirements:

? ? ? ①: Want to filter out age>25 some people.

? ? ? ②: Sometimes there are too many people in the person array, and I want to add a Count property to indicate it.

For the above requirements, the group is still very good, because the group has so two optional parameters: Condition and finalize.

? ? ????????? Condition: This is the filter condition. (similar to having a having in Oracle) the filter condition is almost the same as the above find, not much to say.

? ????????? Finalize: This is a function, each set of documents after the execution, many will trigger this method, then in each set of collections plus count is its life. Statistic count, cool turn. Out is the document after grouping. (similar to finally)

???????? Example:

???????????? Db.user.group ({

Key:{age:true},

Initial:{person:[]},

$reduce: Function (Cur,prev) {

???? Prev.person.push (Cur.name);

},

condition:{age:{$gt: 18}},

Finalize:function (out) {

???? Out.count = Out.person.length;

}

});

?

?

???? Mapreduce????

???????? This is the most complex of the aggregation functions, but the more complex the more flexible.

? mapReduce is actually a programming model, used in distributed computing, where there is a "Map" function, a "reduce" function.

? ? ① Map :

? ? ? ? ? This is called the mapping function, which calls emit (Key,value) , the collection will follow your assigned Key group the mappings.

? ? ② Reduce :

? ? ? ? ? This is called the simplification function, which Map Grouped data for group simplification, note: in reduce (key,value) in the Key is that

???? Emit in the Key , Vlaue to be Emit after grouping the emit (value) the collection, here is also a lot {"Count": 1} the array.

? ? ③ MapReduce:

? ? ? ? ? This is the last function to execute, the parameter is Map , Reduce and some optional parameters. See figure:

??

We can see the following information:

????? Result: " set name of the store " ;

????? Input: the number of incoming documents.

? ??? emit : The number of times this function was called.

????? Reduce : The number of times this function was called.

???? ? output: returns the number of documents at the end.

Finally, let's take a look "Collecton" the case in which the collection is grouped by name.

?

?

4. Cursors

???? the cursor inside the MongoDB is somewhat similar to what we call a deferred execution in C # , such as:

? ? ? ???????? var list=db.user.find ();

for such an operation,Listactually did not get to Personin the document, but to declare a"Query Structure"by the time we need it. fororNext ()load it up once.(or enter directlyListViewListof Data), and then let the cursor read line by row, and when we're done enumerating, the cursor is destroyed, and then we passListwhen retrieved, no data was found to be returned.

????

??

Of course, our " Query Constructs " can also make a complex point, such as paging, sorting can be added.

????????? var single=db.person.find (). Sort ({"Name", 1}). Skip (2). Limit (2);

so that's"Query Constructs"can be executed when we need to execute, greatly increased unnecessary expenses. but never mind . : Because of this characteristic of the cursor, sometimes thelist is not loaded when the program is written, and we use it. An error that causes a null pointer to be reported in the program. I've come across it . , so always be aware ofListloading time so as not to be unnecessarilyBugtrouble.

?

MongoDB Common Data manipulation

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.