插入(insert())
字段名在创建时有以下限制
1.字段名_id为系统预留字段,系统默认主键,所以它的值必须是唯一的。
2.字段名第一个字符不能为 $ 字符
3.字段名不能包含 . 字符
insert()函数原型
db.collection.insert( <document> )
例子1:插入
db.test.insert(
{
_id:1,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
) |
db.test.insert(
{
_id:1,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
)
例子2:批量插入
db.test.insert(
[
{
_id:1,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
},
{
_id:2,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
]
) |
db.test.insert(
[
{
_id:1,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
},
{
_id:2,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
]
)
更新插入(update())
1. 如果查询匹配一个现有的文档,执行更新操作
2. 如果查询匹配集合中没有文档,执行插入操作。
update()函数原型
db.collection.update( <query>, <update>, { upsert: true } )
例子3:更新插入
db.test.update(
{_id:5},
{
user:{first:'fengdingbo',last:'qiufeng'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
},
{upsert:true}
) |
db.test.update(
{_id:5},
{
user:{first:'fengdingbo',last:'qiufeng'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
},
{upsert:true}
)
例子4:更新插入(save())
db.test.save(
{
_id:10,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
) |
db.test.save(
{
_id:10,
user:{first:'qiufeng',last:'fengdingbo'},
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
)
MongoDB shell:循环执行100次插入
for(var i=1;i<=100;i++){
db.test.insert(
{
_id:i,
user:{first:'qiufeng',last:'fengdingbo'},
age:1,
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
)
} |
for(var i=1;i<=100;i++){
db.test.insert(
{
_id:i,
user:{first:'qiufeng',last:'fengdingbo'},
age:1,
birth:Date('Dec 08, 1984'),
like:['php','perl','python']
}
)
}
官网手册:http://docs.mongodb.org/manual/applications/create/