1. Basic concepts of Mongodb
1. Naming rules of Mongodb database:
cannot be an empty string ("")
must not contain '' (space), ., $, /,, and
D:mongodbbin>mongo
Alternatively, navigate to C:mongobin in Windows Explorer and double-click mongo.exe.
No matter which method you choose to start the shell will appear
MongoDB shell version: 1.6.5
connecting to: test
>
Now connected to the test server.
2.MongoDB installation and configuration under Linux
1. For 32-bit linux
$ curl http://downloads.mongodb.org/linux/mongodb-linux-i686-1.4.4.tgz > mongo.tgz
$ tar xzf mongo.tgz
For 64-bit linux
$ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.4.4.tgz > mongo.tgz
$ tar xzf mongo.tgz If not To install curl, first install apt-get install curl
2. Create a data folder. By default, MongoDB will store data in the /data/db/ folder. This folder needs to be created manually. Create it as follows: $ adduser mongodb $ passwd mongodb $ sudo mkdir -p /data/db/ $ sudo chown `id -u` /data/db $ chown -R mongodb:mongodb /data Of course, you can specify it through the --dbpath command MongoDB stores data in another directory.
3. Let the database run in the console: $ nohup ./mongodb-xxxxxxx/bin/mongod & $ ./mongodb-xxxxxxx/bin/mongo > db.foo.save( { a : 1 } ) > db.foo The result of .find() is: { "_id" : ObjectId("4cd181a31415ffb41a094f43"), "a" : 1 } OK! !
Two. Mongodb instructions and related operations
a) show command
ii. Enter show db in dos to view all current databases
> show dbs
admin
alphabet
color
colors
local
mymongo
test
>
iii. show collections view All tables under the current database
> use mymongo
switched to db mymongo
> show collections
colors
shell.colors
system.indexes
>
b) use command
i. Specify the database you need to use currently, if not, Create a new library. If there is no data in this library, the system will be destroyed after a period of time
ii. use [databaseName]
c) insert command
i. Add data, the data format is json format
ii. If there is no table in the data added by insert, then A new table will be created and data will be added to the table
iii. db.[table name].insert()
> db.dingdan.insert(
... {
... order_id: 109384,
.. . Order_date: new Date("12/04/2010"),
... customer: {
... name: "Joe Bloggs",
... company: "XYZ Inc.",
... phone : "(555) 123-4567"
... },
... payment: {
... type: "Cash",
... amount: 4075.99,
... paid_in_full: true
.. . price_per_unit : 75.99,
... }, {
... sku: "XYZ3400",
... description: "An expensive product",
... quantity: 2,
... price_per _unit: 2000
.. .}, ...], c ... cashier_id: 340582242
...}
...)
D) Save instructions
Ii. Save data
Ii. If there is no data in the table into the table
iii. If this data exists in the table, modify the new data
iv. db.[table name].save()
db.collection.save( x )
x is the object to be updated, only Can be a single record.
If there is already a record with the same "_id" as the x object in the collection. Mongodb will replace the existing record in the collection with the x object, otherwise the x object will be inserted. If there is no _id in x, the system will automatically generate one and insert it. It is equivalent to the situation of upsert=true and multi=false in the update statement above.
db.test0.save({count:40,test1:"OK"}); _id system will generate
db.test0.save({_id:40,count:40,test1:"OK"}); if test0 If there is an _id equal to 40, it will be replaced, otherwise it will be inserted.
e) remove command
i. Delete a specified piece of data in the table
ii. db.[table name].remove()
Add a record in the colors table
> db.colors.save({"color": "112233"})
> db.colors.find()
{ "_id" : ObjectId("4e9bc2024fadb58af17b2f01"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2374fadb58af17b2f02"), "color " : "ff0000" }
{ "_id" : ObjectId("4e9bc2384fadb58af17b2f03"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2394fadb58af17b2f04"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2394fadb58af17b2f05"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23a4fadb58af17b2f06"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9b c23a4fadb58af17b2f07 "), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23b4fadb58af17b2f08"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23b4fadb58af17b2f09"), "color" : " ff0000" }
{ "_id" : ObjectId("4e9bc23c4fadb58af17b2f0a"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23c4fadb58af17b2f0b"), "color" : "ff0000" }
{ " _id" : ObjectId("4e9bc23d4fadb58af17b2f0c"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9e3f435240000000005a2d"), "color" : "112233" }
Delete the added record
> db.colors . remove({"color":"112233"})
> db.colors.find()
{ "_id" : ObjectId("4e9bc2024fadb58af17b2f01"), "color" : "ff0000" }
{ "_id" : ObjectId( "4e9bc2374fadb58af17b2f02"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2384fadb58af17b2f03"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2394fadb58 af17b2f04"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc2394fadb58af17b2f05"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23a4fadb58af17b2f06"), "color" : "ff0000" }
{ " _id" : ObjectId("4e9bc23a4fadb58af17b2f07"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23b4fadb58af17b2f08"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9b c23b4fadb58af17b2f09" ), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23c4fadb58af17b2f0a"), "color" : "ff0000" }
{ "_id" : ObjectId("4e9bc23c4fadb58af17b2f0b"), "color" : "ff0000 " }
{ "_id" : ObjectId("4e9bc23d4fadb58af17b2f0c"), "color" : "ff0000" }
f) update command
i. Modify data
ii. db.[table name].update()
db.collection .update(criteria, objNew, upsert, multi)
criteria: update query conditions, similar to
objNew after where in sql update query: update object and some update operators (such as $, $inc...) etc., it can also be understood as the
upsert after set in the sql update query: This parameter means whether to insert objNew if there is no update record, true means insert, and the default is false, not insert.
multi: The default value of mongodb is false, which only updates the first record found. If this parameter is true, all multiple records found according to the conditions will be updated.
Example:
db.test0.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } ); Only the first record is updated
db. test0.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true ); All updated
db.test0.update( { "count " : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false ); Only the first one is added
db.test0.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true ); All added
db.test0.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );all updated
db.test0.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );Only updated the first one
g) Find command
i. Query data and can be used with skip and limit methods to achieve paging effect.
ii. db.[table name].find({}).skip([num1]).limit([num2]), num1 starts from which piece of data, num2 is the number of queried data, if there is insufficient data , then the remaining data shall prevail
iii. db.[table name].find({[_id:{ < : num }]}) The brackets are examples of query conditions, and relational operators such as greater than and less than use translation characters replace.
> use zm
switched to db zm
> db.zm.find().skip(10).limit(5);
{ "_id" : ObjectId("4e9e3d6b5240000000005a1c"), "char" : "k", "code" : 107 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1d"), "char" : "l", "code" : 108 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1e"), "char" : "m", "code" : 109 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1f"), "char" : "n", "code" : 110 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a20"), "char" : "o", "code" : 111 }
>
h) findOne command
i. Query the first command in the specified query
ii. db.[table name].findOne()
> db. zm.findOne()
{ "_id" : ObjectId("4e9e3d6b5240000000005a12"), "char" : "a", "code" : 97 }
Note: The O in findOne must be capitalized.
i) function
i. Custom function, you can call it directly after definition
ii. function testFunction(op1,op2,op3……){}
iii. “testFunction” : function(op1,op2,op3……) {}
iv. The defined function can be called directly, and return can be used to return data
> function testFunction(){
... db.zm.remove({"code":{$in:[100,101,102,103]}})
... return db.zm.find({})
... }
> testFunction()
{ "_id" : ObjectId("4e9e3d6b5240000000005a12"), "char" : "a", "code" : 97 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a13"), "char" : "b", "code" : 98 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a14"), "char" : "c", " code" : 99 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a19"), "char" : "h", "code" : 104 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1a"), "char" : " i", "code" : 105 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1b"), "char" : "j", "code" : 106 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1c"), " char" : "k", "code" : 107 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1d"), "char" : "l", "code" : 108 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1e "), "char" : "m", "code" : 109 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a1f"), "char" : "n", "code" : 110 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a20"), "char" : "o", "code" : 111 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a21"), "char" : "p", "code" : 112 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a22"), "char" : "q", "code" : 113 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a23"), "char" : "r", "code" : 114 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a24"), "char" : "s", "code" : 115 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a25"), "char" : "t", "code" : 116 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a26"), "char" : "u", "code" : 117 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a27"), "char" : "v", "code" : 118 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a28"), "char" : "w", "code" : 119 }
{ "_id" : ObjectId("4e9e3d6b5240000000005a29"), "char" : "x", "code" : 120 }
has more
j) var
i. The variable naming type
ii. is the same as var in JS.
1. var [name] naming is also consistent with js variable naming rules.
k) print command
i. Used for printing
ii. print([Strings]);
iii. If the print object is mongo data, it will not be recognized.
l) printJson command
i. Used to print data
ii. printJson([json]);
m) shutdown
i. Stop mongodb
ii. >use database name
switched to do admin
>db.shutdownServer ();
server should be down…
MongoDB supports various conditional operators, including:
? $lt (less than)
? $lte (less than or equal to)
? $gt (greater than)
? $gte (greater than or equal to)
? $all (match all values in the array)
? $exists (check if the field exists)
? $mod (modulus)
? $ne (not equal)
? $in (match one or more values in the array
? $type (matches values with the specified BSON data type)
? $not (not equal to)
db.tablename.find({fieldname:{$gt:100}})
mongodb update operator:
1 ) $inc
Usage: { $inc : { field : value } }
means adding value to a numeric field, for example:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 16, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 1 } } );
> db.test0.find( { "_id" : 15 } );
{ " _id" : { "floatApprox" : 15 }, "count" : 17, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", " test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : 2 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 19, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", " test4" : "OK", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $inc : { "count" : -1 } } );
> db .test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : "TESTTEST", "test2" : "OK", "test3" : "TESTTEST", "test4" : "OK", "test5" : "OK" }
2) $set
Usage: { $set : { field : value } }
is equivalent to SQL's set field = value, all data types support $set. Example:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : "testv1","test2" : "testv2","test3" : "testv3","test4" : "testv4" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : " testv1", "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
3) $unset
Usage: { $unset : { field : 1} }
As the name suggests, it is to delete the field. Example:
> db.test0.update( { "_id" : 15 } , { $unset : { "test1":1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test2" : "testv2", "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $unset : { "test2": 0 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test3" : "testv3", "test4" : "testv4", "test5" : "OK" }
> db.test0. update( { "_id" : 15 } , { $unset : { "test3":asdfasf } } );
Fri May 14 16:17:38 JS Error: ReferenceError: asdfasf is not defined (shell):0
> db.test0.update( { "_id" : 15 } , { $unset : { "test3":"test" } } );
> db.test0.find( { "_id" : 15 } );
{ " _id" : { "floatApprox" : 15 }, "count" : 18, "test4" : "testv4", "test5" : "OK" }
I didn't see what the 1 in field : 1 is for, anyway. As long as there is something.
4) $push
Usage: { $push : { field : value } }
Append the value to the field. The field must be an array type. If the field does not exist, a new array type will be added. . Example:
> db.test0.update( { "_id" : 15 } , { $set : { "test1" : ["aaa","bbb"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1": "ccc" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test2": "ccc" } } );
> db.test0 .find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $push : { "test1 ": ["ddd","eee"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5 " : "OK" }
5) $pushAll
Usage: { $pushAll : { field : value_array } }
Same as $push, except that multiple values can be appended to an array field at one time. Example:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", " bbb", "ccc", [ "ddd", "eee" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0 .update( { "_id" : 15 } , { $pushAll : { "test1": ["fff","ggg"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "aaa", "bbb", "ccc", [ "ddd", "eee" ], "fff" , "ggg" ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
6)$addToSet
Usage: { $addToSet : { field : value } }
Add a value to the array, and only add it if the value is not in the array. Example:
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": {$each : ["444","555"] } } } );
> db.test0 .find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [
"aaa",
"bbb",
"ccc ",
[
"ddd",
"eee"
],
"fff",
"ggg",
[
"111",
"222"
],
"444",
"555"
], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $addToSet : { " test1": {$each : ["444","555"] } } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [
"aaa",
"bbb",
"ccc",
[
"ddd",
"eee"
],
"fff",
"ggg ",
[
"111",
"222"
],
"444",
"555"
], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [
"aaa",
"bbb",
"ccc",
[
"ddd",
"eee"
],
"fff",
"ggg",
[
"111",
"222"
],
"444",
"555",
[
"444",
"555"
]
], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id " : 15 } , { $addToSet : { "test1": ["444","555"] } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [
"aaa",
"bbb",
"ccc",
[
"ddd",
"eee"
],
" fff",
"ggg",
[
"111",
"222"
],
"444",
"555",
[
"444",
"555"
]
], "test2 " : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
7) $pop
Delete a value in the array
Usage:
Delete the last value: { $pop : { field : 1 } }
Delete the first value: { $pop : { field : -1 } }
Note that you can only delete one value, which means you can only use 1 or -1, not Use 2 or -2 to delete two items. Only mongodb 1.1 and later versions can be used, for example:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, " test1" : [
"bbb",
"ccc",
[
"ddd",
"eee"
],
"fff",
"ggg",
[
"111",
"222"
],
"444"
], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": -1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [
"ccc",
[
"ddd",
"eee"
],
"fff",
"ggg",
[
"111",
"222"
] ,
"444"
], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pop : { "test1": 1 } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18 , "test1" : [ "ccc", [ "ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], " test4" : "testv4",
"test5" : "OK" }
8) $pull
Usage: $pull : { field : value } }
Delete a value equal to value from the array field. Example:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ " ddd", "eee" ], "fff", "ggg", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4",
"test5" : "OK" }
> db.test0.update( { "_id" : 15 } , { $pull : { "test1": "ggg" } } );
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ "ddd", "eee" ], "fff", [ "111 ", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
9) $pullAll
Usage: { $pullAll : { field : value_array } }
Same as $pull, you can delete multiple values in the array at one time. Example:
> db.test0.find( { "_id" : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ "ccc", [ " ddd", "eee" ], "fff", [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5"
: "OK" }
> db.test0.update( { "_id" : 15 } , { $pullAll : { "test1": [ "ccc" , "fff" ] } } );
> db.test0.find( { "_id " : 15 } );
{ "_id" : { "floatApprox" : 15 }, "count" : 18, "test1" : [ [ "ddd", "eee" ], [ "111", "222" ] ], "test2" : [ "ccc" ], "test4" : "testv4", "test5" : "OK" }
10) $ operator
$ is his own meaning, which means to find out according to conditions An item in the array is itself.
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }
> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1} }, false, true )
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC", "comments" : [ { "by" : "joe", " votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }
It should be noted that $ will only apply the first array item found, and the rest will be ignored. Let's look at the example:
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2 }, {$inc: {"x.$": 1}}, false, true);
> t.find();
Also note that when $ is used with $unset, a null will be left array items, but you can use {$pull:{x:null}} to delete all array items that are null. Example:
> t.insert({x: [1,2,3,4,3,2,3,4]})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, 3, 4, 3, 2, 3, 4 ] }
> t.update({x:3}, {$unset:{"x.$":1}})
> t.find()
{ "_id" : ObjectId("4bde2ad3755d00000000710e"), "x" : [ 1, 2, null, 4, 3, 2, 3, 4 ] }
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }
Creation of index in Mongodb:
db.[table name].ensureIndex({num1: 1,num2 :-1}) num1 and num2 are the fields used to create an index. When building an index, you need to consider the following questions:
(1). What kind of query will be done? Which keys need to be indexed?
(2). What is the index direction of each key?
(3). How to deal with expansion? Is there a different arrangement of keys that would keep more of the frequently used data in memory.
db.[table name].ensureIndex({num1: 1,num2:-1}, {"background":true})//Modify long-standing index
db.runCommand({"dropIndexes": "foo", "index":"alphabet"})
If you want to delete all indexes, you can assign the value of index to *.
Master-slave replication in Mongodb
Master-slave replication can be used for database backup, failure recovery, read expansion, etc. (There is currently no mechanism to replicate from slave nodes).
1. Run mongod –master to start the master server
2. Run mongod –slave –source master_address to start the slave server. (master_address is the address of the master node)
3. Create a directory for the master node and bind the port (10000):
$mkdir –p ~/dbs/master
$ ./mongod –dbpath ~/dbs/master –port 10000 –master
4. Set the slave node directory (select a different directory and port)
$mkdir –p ~/dbs/slave
$ ./mongod –dbpath ~/dbs/slave –port 10001 –slave –source
localhost: 10000
Options: -only (specify to only copy a specific database from the slave node)
-slavedelay (used on the slave node to increase the delay when applying the operations of the master node)
-fastsync (based on the data snapshot of the master node) Start the slave node and implement master-slave synchronization)
-autoresync (automatically restore master-slave synchronization)
-oplogSize (the size of the master node oplog in MB)
Three. GridFS of Mongodb
Because mongodb supports massive data storage, mongodb also comes with a distributed file system, GirdFS, which can support massive data storage. There is also a BSON document object in mongodb with a maximum size of 4MB, which can store large amounts of data. Object. Even without size restrictions, BSON cannot satisfy fast range queries on big data, so mongodb introduced GridFS.
4. Test with code in PHP:
Like MySQL, mongoDB is integrated with PHP in the form of a PHP extension library .dll.
Go to the following website to download the dll file of the corresponding PHP version under Windows:
http://cn.php.net/manual/en/mongo.installation.php#mongo.installation.windows
According to your PHP version and whether it is threaded Security (can be viewed in phpinfo), etc. to select the corresponding version to download, unzip it, and get the php_mongo.dll file. Copy it to the ext directory in the PHP installation directory. Add: extension = php_mongo.dll to the php.ini file;
Restart the web server (apache or nginx). You should be able to see mingoDB information in phpinfo, otherwise there is an installation problem. It is possible that the downloaded mingoDB extension is incorrect.
Php operates mongodb
1. Establish a connection with mongoDB:
Directly instantiate the mongo class + create a connection:
$mo = new Mongo();//Get a Mongo connection object
Instantiate a Mongo class and connect it with the default Establish a connection to mongoDB on localhost:27017 port.
If you want to connect to other hosts, you can write like this:
$mongo = new Mongo("mongodb://username:password@192.168.1.22:12345");
Another way is to instantiate the mongo class and then manually Establish a connection:
$mongo= newMongo("mongodb://username:password@192.168.1.22:12345",array('connect'=>false));//Initialization class
$mongo->connect();/ / Create connection
Some useful methods in the Mongo class:
Mongo::listDBs()
Returns an array containing library (DB) information on the current mongo service.
$mo = new Mongo();
$dbs = $mo->listDBs();//Get an array containing db information
Mongo::selectCollection($db,$coll)
Returns an array under the current connection collection object in db.
$mo = new Mongo();
$coll = $mo->selectCollection('db','mycoll');//Get a collection object
Select the desired database (Mongo class):
One way:
$mongo = new Mongo();
$db = $mongo->foo;//Get a MongoDB object
Another way:
$mongo = new Mongo();
$db = $mongo->selectDB( 'foo');//Get a MongoDB object
Useful functions in MongoDB:
Create a MongoDB object
$mo = new Mongo();
$db = new MongoDB($mo,'dbname');//Pass Create a MongoDB object
Delete the current DB
$db = $mo->dbname;
$db->drop();
Get the current database name
$db = $mo->dbname;
$db->_tostring ();
Select the desired collection:
A:
$mo = new Mongo();
$coll = $mo->dbname->collname;//Get a collection object
B:
$db = $mo ->selectDB('dbname');
$coll = $db->collname;
C:
$db = $mo->dbname;
$coll = $db->selectCollectoin('collname');//Get A collection object
Insert data (MongoCollection object):
MongoCollection::insert(array $a,array $options)
array $a The array to be inserted
array $options options
safe whether to return operation result information
fsync whether to insert directly into the physical hard disk
$coll = $mo->db->foo;
$a = array('a'=>'b');
$options = array('safe'=>true);
$rs =$coll- >insert($a,$options);
$rs is an array type array, containing operation information
Delete records in the database (MongoCollection object):
MongoCollection::remove(array $criteria,array $options)
array $criteria Condition
array $options Options
safe Whether to return the operation result
fsync Whether it directly affects the physical hard disk
justOne Whether it only affects one record
$coll = $mo->db->coll;
$c = array( 'a'=>1,'s'=>array('$lt'=>100));
$options = array('safe'=>true);
$rs = $coll->remove($c ,$options);
$rs is an array type array, containing operation information
Update records in the database (MongoCollection object):
MongoCollection::update(array $criceria,array $newobj,array $options)
array $ criteria Conditions
array $newobj Content to be updated
array $options Options
safe Whether to return the operation result
fsync Whether it directly affects the physical hard disk
upsert Whether to add a new one if there is no matching data
multiple Whether it affects all records that meet the conditions , only one item is affected by default
$coll = $mo->db->coll;
$c = array('a'=>1,'s'=>array('$lt'=>100));
$newobj = array('e'=>'f','x'=>'y');
$options = array('safe'=>true,'multiple'=>true);
$rs = $ coll->remove($c,$newobj,$options);
$rs is an array type array, containing operation information
Query the collection to obtain a single record (MongoCollection class):
array MongoCollection::findOne(array $query, array $fields)
array $query condition
array $fields The fields to be obtained
$coll = $mo->db->coll;
$query = array('s'=>array('$lt'=> 100));
$fields = array('a'=>true,'b'=>true);
$rs = $coll->findOne($query,$fields);
If there is a result, return an array , if there is no result, return NULL
Query collection to obtain multiple records (MongoCollection class):
MongoCursor MongoCollection::find(array $query, array $fields)
array $query condition
array $fields Fields to be obtained
$ coll = $mo->db->coll;
$query = array('s'=>array('$lt'=>100));
$fields = array('a'=>true,'b' =>true);
$cursor = $coll->find($query,$fields);
Returns a cursor record object MongoCursor.