MongoDB01

MongoDB is a document-oriented database

Document primary key
unique primary key of the document
support all data types (except arrays)
composite primary key

 

Objects primary key ObjectId
default document primary key
to quickly generate a 12-byte id
includes creation time

 

Use the mongo shell

 

Create a document
db.collection.insertOne ()

db.<collection>.insertOne(
<document>,
{
writeConcern:<document>
}
)

writeConcern document defines the security of this document creation write level, security level interpretation write a database write operation is successful, the higher the level, the lower the risk of loss, delay write operations may be higher


Array operators
{<field>: {$ all : [<value1>, <value2> ...]}}

{<field>:{$elemMatch:{<query1>,<query2>,...} } }

 

Screening document
{<Field>: {: / pattern / ,: '<Option>'}}
{<Field>: {: / pattern / <Options>}}

 

And when used in conjunction operator in $, it can only be used / pattern / <options>
reads the user's name or bank c to the beginning of the document object J
db.accounts.find ({name: {$ in: [/ ^ c / , / ^ j /]}} )

 


Contains the user's name read LIE (case insensitive) bank documents
db.accounts.find ({name: {$ regex : / LIE /, $ options: 'i'}})

 

 

 

Documentation cursor

db.collection.find () returns a collection of documents without cursor iteration of cursor, list only the first 20 document

Use the cursor to access the index set a document
> = var MyCursor db.accountd.find ();
MyCursor [0]

 

The cursor will automatically turn off after 10 minutes
can be used noCursorTimeout () function to hold the cursor has been effectively
> var myCursor = db.accounts.find (). NoCursorTimeout ()

Initiative to close the cursor
> myCursor.close ()

 

cursor.hasNext () there are not set travel documents, returns true
document cursor.next () a pointer on the next set of documents

>var myCursor = db.accounts.find({ name:"lihua" });
while(myCursor.hasNext()) {
printjson(myCursor.next())
}

 

cursor.forEach(<function>)

var myCursor = db.accounts.find({name: "lihua"});
myCursor.forEach(printjson)

 

cursor.limit(<number>)
cursor.skip(<offset>)
>db.accounts.find ({name:"lisi"}).limit(1)

 

count function

cursor.count (<applySkipLimit>)
By default, <applySkipLimit> is false, i.e. cursor.count () does not consider cursor.skip () and
cursor.limit () effect

Sort Sort -1 1 Forward reverse order
cursor.sort (<docment>) document defined in claim ordered
according to descending balance of a bank account user names are arranged in alphabetical order of the document mode
> db.accounts.find (). Sort ( {balance: -1, name: 1 })


Reading the bank account balance of the largest document
> db.accounts.find () sort ({balance : -1}). .Limit (1)


cursor.skip () in cursor.limit () performed before
cursor.sort () in cursor.skip () and cursor.limit performed before ()

sort->skip->limit

 

Document projection
db.collection.find (<query>, <projection >)
when not using the projector, db.collection.find () returns the complete document matching the filter
using the projector can selectively returning some of the fields in the document
{field : Inclusion}
. 1 represents a return to field, the field that return 0

>db.accounts.find( { }, {name:1} )

The default return the document primary key

>db.accounts,.find({ }, { name:1,_id:0 } )

In addition to the primary key document, the document can not be used in the primary key comprises mixing, both with and without the projection operation or list all fields should be included in the projected document, or list all fields should not contain


Using a projection on the array field
$ Slice operator may return part of the element in the array field


> db.account.find ({}, {_ id: 0, name: 1, contact: {$ slide: 1}}) // contact the first element in the array
contact: {$ slide: -1} // contact the first element in the array reciprocal
contact: {$ slide: [1,2 ]}


and $ elemMatch operator may return an array that satisfies the filter criteria field of the first element

db.accounts.find({ },
contact:{ $elemMatch:{ $gt: "Ireland "}}
)

 

Update document

db.collection.update ()

db.<collection>.update(<query>,<update>,<options>)

If the <update> document does not contain any updates operator, db.collection.update (), you will use the <update a set of documents that match a direct replacement, <query> screening conditions set

Alice changed to the account balance 200 is
> db.accounts.update ({name: "alice"}, {name: "alice", Blance: 200 is})


Document _id primary key can not be changed

In use <update> Replace the entire document when the document is updated, only the first chapter in line with <query> document will be updated

Document account account balance inquiries between 20 and 80
> db.account.update ({balance: {$ gt: 20, $ lt: 80}}, {name: "bill", blance: 50, gender: "M "})

 

Update specific fields


$ set update or add fields
$ remove the unset field
$ rename the rename field
$ inc is acceleration field
$ field multiplied by MUL
$ field value reduced compared min
$ max comparison field value increases

 

 

Update operator
{$ set: {<field1> : <value1>, ...}}

 

>db.accounts.update (
{name: "jack"},
{$set:
{
"contact.5": "new contact"
}

}
)

If you add a new value to a location outside the scope of the existing array field, the field will be expanded length of the array, the array members are not assigned null set


{$ unset: {<field1> : "", ...}}
Delete field

>db.accounts.update(
{ name : "jack"},
{$unset:
{
balance:""
}
}
)

Assignment $ unset command ( "") has no effect on the operating result

$ Unset command field does not exist, then the content of the document will remain unchanged

When one of the unset $ element array, the length of the array does not change, the value is reset


{$ rename: {<field1> : <newName1>, <field2>:... <newName2>,}}
rename the fields
$ the rename command to rename the field does not exist, does not change the content of the document

If the new field name already exists, then the field will be covered by the original

$ Rename command in the old fields and new fields can not point to an array element


Update field values
{$ inc: {<field1> : <amount1>,}...} // subtract field
{$ mul: {<field1> :... <Number1>,}} // multiplied

Updated account balance
> db.accounts.update (
{name: "David"},
{$ inc is:
{
Balance: -0.5
}
}
)

$ inc and $ mul commands can only be used in numeric fields
If the field does not exist to be updated, $ inc will create fields, and field values to increase or decrease the value of the command, and $ mul creates a field, but will field value is set to 0


After updating the comparison field values
{$ min: {<field1>: <VALUE1>,}...}
{$ Max: {<field1>:... <VALUE1>,}}

Before updating the multi-compare operation to return to smaller or larger field
if the field does not exist to be updated, $ min and $ max will create fields, and field value is set to update the value of the command


If not updated, and the updated value type field types, $ min and $ max command are compared according to the type of data collation BSON


Update the array operator

$ addToSet add elements to the array
$ pop removing elements to the array
$ pull to the array selectively remove elements
$ pullAll
add elements to the array $ push

Add Contact to Li Hua's account documentation
> db.accounts.update (
{name: "Lihua"},
{$ addToSet: {concat: "China"}}
)

If the value to be inserted already exists in the array field, the $ addToSet not add duplicate values


When using $ addToSet array and insert the document, insert the value in the order of fields and also has value when repeated, it was counted as duplicates ignored

$ addToSet array insert will be updated in the array field, become embedded in the array
if you want to add to the array field between the plurality of elements, is required $ each operator


>db.accounts.update(
{name: "lihua"},
{$addToSet:{contact:{ $each: ["contact1","contact2" ] } } }
)

 

Remove elements from the array field
{$ pop: {<field> : <-1 | 1>,}...}

Delete the last contact from Li Hua's account documentation
> db.accounts.update (
{name: "Lihua"},
{$ POP: {Business Card: 1}}
)

$ pop operators can only be used in an array of fields
after removed the last element in the array, it will leave empty array

Remove certain elements from the array field
{$ pull: {<field1>: <value | for condition Condition>,}...}
{$ Pull All: {<field1>: [<VALUE1>, <value2>...], .}.}


{$pullAll :{<field1>: [<value1>,<value2> ] } }     <=>    {$pull : {<field1>: {$in: [<value1>,<value2> ] } } }


If you want to remove the element is an array value and the order of array elements must be removed and an array of
exactly the same


$ PullAll command will delete document elements of fields and field order in which they are exact match

$ pull command deleting documents comprising document element specified fields and field values of
the field need not be fully match the order


Add a field to the array field
{$ push:... { <Field>, <value1>,}}

, and $ addToSet commands, if $ Push specified in the command array field does not exist, this field will be added to the original document

 

 

Update specific elements in the array
db.collection.update (
{<Array>: <Query Selector>},
{<Update operator>:. "<Array> $" {:}} value
)


$ Array is a placeholder for the first array element of matching the filter
with the update operators to use, can be updated to meet the filter criteria of the array elements


See Hua bank documents
> db.accounts.find (
{name: "Lihua"},
{name:. 1, newArray:. 1, the _id: 0}
) .pretty ()

{
"name": "lihua",
"newArray":[
"push2",
"push1"
]
}


>db.accounts.update(
{name: "lihua",
newArray: "pos2"
},
{
$set:{
"newArray.$":"update"
}
}
)


Update all elements in the array
{<update operator>: { " <array> $ [].": Value}}

$ [] Refer to the elements of all the elements


>db.accounts.update (
{name: "lihua"},
{$set:{
"contact.0.$[ ]" : "111111111"
}}
)

 


Update the document
db. <Collection> .update (< query>, <update>, <options>)

<Option> more options update command

updat correspond to a command to use a filter condition corresponds to only a document. By default, even if the filter criteria correspond to multiple documents, update command is still only update a document

Multi {: <boolean>}
Multi option to update multiple documents that meet the filter criteria
> db.accounts.update (
{},
{$ the SET: {
a Currency: "USD"
}},
{Multi: to true}
)


MongoDB single document can only guarantee atomicity operation, a plurality of documents can not be guaranteed atomicity operations

 

Delete documents
db.collection.remove ()

db.<collection>.remove(<query>,<options>)


Delete the balance of bank documents 50
db.collections.remove ({balance: 50})

remove command removes all documents matching the filter, if you only want to delete meet the filter criteria of the first chapter document, you can use justOne options


>db.accounts.remove(
{balance: {$lt: 100} },
{justOne: true }
)


删除集合
db.collection.drop()
db.<collection>.drop({writeConcern: <document> } )

If the number of documents in the collection efficiency of a lot, use the remove command to delete all of the document is not high, in this case, a more effective method
is to drop the command to re-establish the document, rebuild the index

 

Guess you like

Origin www.cnblogs.com/quyangyang/p/11326618.html
01