Mongodb 学习笔记

来源:互联网 发布:台湾网络电视在线直播 编辑:程序博客网 时间:2024/05/17 04:51
Docs: https://docs.mongodb.org/manual/reference/database-references/
Docs: https://docs.mongodb.org/manual/reference/command/


----install mongo---
1.运行安装包
2.将mongodb的安装位置配置入path


----start db-------
1.cmd
2.mongod --dbpath  数据文件的位置 [--auth]




----use command line--
1.mongo
2.use dbname


-----create db-----
1.use dbname
2.show dbs  (查看所有数据库)




-----db management-----
Privileges:


privileges: 
[

resource: { 
db: "dbName" , 
collection: "collectionName" 
},
actions: [ "find", "createCollection", "dbStats", "collStats" ] 
}  
...
],



Role: 
---- opt role---
read
readWrite

----  data administration role---
dbAdmin
dbOwner
userAdmin

---- cluster administration roles----
clusterAdmin
clusterManager
clusterMonitor
hostManager

---- backup adn restoration role----
backup
restore

---- all database roles----
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

---- supperuser roles----
root

---- internal role
system




Create Role:


db.createRole(
{ role: "specifyRole",
 privileges: [
详细见上
 ],
 roles: [
详细见上
 ]  
},
{w: "majority", wtemeout: 5000}
)

db.updateRole(
"<rolename>",
{
privileges:
[

],
roles:
[
]
},
{w: "majority", wtemeout: 5000}
)

db.dropRole( "roleName", { w: "majority" } )



Create User:


db.createUser( 

"user" : "account",
            "pwd": "password",
            "customData" : { employeeId: 12345 },
            "roles" : [ 
{ role: "clusterAdmin", db: "admin" },
                { role: "readAnyDatabase", db: "admin" },
                "readWrite"
]
},
        { w: "majority" , wtimeout: 5000 }
)


db.updateUser(
  "username",
  {
customData : { xxx },
roles : [
  { role: "<role>", db: "<database>" } 
],
pwd: "password"
}
)

db.changeUserPassword("user", "new password")

db.removeUser(username)




-------------MongoDB设计模式的一些考虑----------


1.可根据用户要求设计架构。


2.合并对象为一个文件,如果要将它们放在一起。否则分开它们(但确保不需要连接)。


3.重复数据(有限),因为磁盘空间便宜(相比计算时间)。


4.不需要连接写入,而是读。


5.优化架构是最常见的用例。


6.在模式上做复杂的聚集。




------- Create Collections ----------
1. db.collection.insert({
xx : xx
...
})


2.  db.collection.find() 
db.collection.findOne()

db.collection.find({
xxx : xx,
xxx : {
$in : ['a','b']
}
}) 

db.collection.find({

$or: [{xxx : {$gt: 100}}, {xxx : {$lt: 9.95}}]

})

3. opt query

Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$in Matches any of the values specified in an array.
$nin Matches none of the values specified in an array.

$or Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
$and Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
$not Inverts the effect of a query expression and returns documents that do not match the query expression.
$nor Joins query clauses with a logical NOR returns all documents that fail to match both clauses.


$exists Matches documents that have the specified field.
$type Selects documents if a field is of the specified type.

$mod Performs a modulo operation on the value of a field and selects documents with a specified result.
$regex Selects documents where values match a specified regular expression.
text Performs text search.
$where Matches documents that satisfy a JavaScript expression.

$geoWithin Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin.
$geoIntersectsSelects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects.
$near Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near.
$nearSphere Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere.

$all Matches arrays that contain all elements specified in the query.
$elemMatch Selects documents if element in the array field matches all the specified $elemMatch conditions.
$size Selects documents if the array field is a specified size.

$comment Adds a comment to a query predicate.

$ Projects the first element in an array that matches the query condition.
$elemMatch Projects the first element in an array that matches the specified $elemMatch condition.
$meta Projects the document’s score assigned during $text operation.
$slice Limits the number of elements projected from an array. Supports skip and limit slices.

4. db.inventory.update(
{ item: "MNO2" }, //query object
{
 $set: {
category: "apparel",
details: {
model: "14Q3", 
manufacturer: "XYZ Company" 
}
 }   
}
)

5.  db.inventory.remove({})
db.inventory.remove( { type : "food" } 
db.inventory.remove( { type : "food" }, 1 )


Java API 快速学习


1. Insert
db.getCollection("restaurants").insertOne(
        new Document("address",
                new Document()
                        .append("street", "2 Avenue")
                        .append("zipcode", "10075")
                        .append("building", "1480")
                        .append("coord", asList(-73.9557413, 40.7720266)))
                .append("borough", "Manhattan")
                .append("cuisine", "Italian")
                .append("grades", asList(
                        new Document()
                                .append("date", format.parse("2014-10-01T00:00:00Z"))
                                .append("grade", "A")
                                .append("score", 11),
                        new Document()
                                .append("date", format.parse("2014-01-16T00:00:00Z"))
                                .append("grade", "B")
                                .append("score", 17)))
                .append("name", "Vella")
                .append("restaurant_id", "41704620"));

2. Find & Query
db.getCollection("restaurants").find(eq("borough", "Manhattan"));


3. Update
db.getCollection("restaurants").updateOne(new Document("name", "Juni"),
        new Document("$set", new Document("cuisine", "American (New)"))
            .append("$currentDate", new Document("lastModified", true)));


4. Delete
db.getCollection("restaurants").deleteMany(new Document("borough", "Manhattan"));
db.getCollection("restaurants").drop();

5. Aggregation
db.getCollection("restaurants").aggregate(asList(
        new Document("$group", new Document("_id", "$borough").append("count", new Document("$sum", 1)))));



Spring data template:
1. Insert
mongoTemplate.insert(object, "collection");


2. Find & Query



3. Update


4. Delete
0 0
原创粉丝点击