#启动mongod db 服务
mongod --config /usr/local/etc/mongod.conf &
#正式环境启动 mongo db 服务
mongod --bind_ip=127.0.0.1 --auth --config /usr/local/etc/mongod.conf &
#mongo db 创建超级管理员
db.createUser(
{
user: "fafa",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
db.createUser(
{
user: "fafa",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
mongo --port 27017 -u "fafa" -p "abc123" --authenticationDatabase "admin"
#mongodb创建普通管理员-某个db
db.createUser(
{
user: "tester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
#链接mongo db 数据库
mongo --port 27017 -u "tester" -p "xyz123" --authenticationDatabase "test"
#mongodb 创建集合
db.createCollection(name, options)
#mongo db常用查询语句
db.myCollection.find()
db.myCollection.find().pretty()
db.myCollection.findOne()
#mongodb 分页查询
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
#mongodb aggregate 联表查询
#$lookup 联表查询,
#$match 过滤查询条件
#$unwind 变成独立数据
db.product.aggregate([
{
$lookup:
{
from:"orders",
localField:"_id",
foreignField:"pid",
as:"inventory_docs"
},
},
{ $match : { price : {$gt:20} } },
{ $unwind:"$inventory_docs" },
{ $project: {inventory_docs:1,_id:0}}
])
#mongodb 多联表查询(涉及3个表)
db.product.aggregate([
{
$lookup:
{
from:"orders",
localField:"_id",
foreignField:"pid",
as:"inventory_docs"
}
},
{
$lookup:
{
from:"comments",
localField:"_id",
foreignField:"pid",
as:"comments_docs"
}
},
{ $match : { price : {$gt:20} } },
{ $unwind:"$comments_docs" }
])
#mongodb 联表查询,设置查询的字段
db.product.aggregate([
{
$lookup:
{
from:"orders",
localField:"_id",
foreignField:"pid",
as:"inventory_docs"
},
},
{ $match : { price : {$gt:20} } },
{ $project: {inventory_docs:1,_id:0}}
])
db.product.aggregate([
{
$lookup:
{
from:"orders",
localField:"_id",
foreignField:"pid",
as:"inventory_docs"
},
},
{ $match : { price : {$gt:20} } },
])
$ops = array(
array(
'$lookup' => array(
"from" => "orders",
"localField" => "_id",
"foreignField" => "pid",
"as"=>"inventory_docs"
)
),
array('$match' => array('price'=>array('$gt'=>20))),
array(
'$project' => array(
"inventory_docs" => 1,
"_id" =>0,
),
),
);
#mongodb 使用关联表里字段进行条件过滤,注意 $match要放在 $unwind后面
db.product.aggregate([
{
$lookup:
{
from:"orders",
localField:"_id",
foreignField:"pid",
as:"inventory_docs"
}
},
{ $match : {"inventory_docs.ordername":"订单4"} },
])
#mongodb 导出
./mongoexport -d my_mongodb -c user -o user.dat
mongodump -h 127.0.0.1 -u fafa -p --db test -out ./test.json