mongodb 操作

1、查询ID最大的数据

以下两种查询方式是一样的结果

db.getCollection('PbocJson').find({}).sort({
_id: -1 // -1为降序排序 1位升序排序
})
.skip(20) //跳过前面或者后面20条 条数可更改
.limit(1) //获取记录的条数 条数可更改

;


db.PbocJson.find({ }) //此处可添加查询条件 格式为json格式 如{id:1,name:"2"}
.sort({
_id: -1 // -1为降序排序 1位升序排序
})
   .skip(20) //跳过前面或者后面20条 条数可更改
.limit(1) //获取记录的条数 条数可更改

2、条件查询

大于等于小于等条件 ($ne,$le,$lte,$gt,$gte)
db.PbocJson.find({ _id: { $ne:
2 //查询id不等于2的数据 } })

like语句(NoSqlBooster客户端,其他如notContains,startWith,endWith notStartWith,notEndsWith)

db.PbocJson.find({
  pbocJson: mb.regex.contains("2")  //pbocJson字段中包含 2 类似于sql语句的like关键字
})

IN语句($nin语句  如not in)

db.PbocJson.find({
pbocJson: {
$in: [1, 2, 3]
}
})

 

exist语句判断字段是否存在

db.PbocJson.find({
_id: {
$exists: true  //true为 exist  false为 not exist
}
})

 

查询某个字段为某种类型的语句(mongodb相同字段可以有不同的类型)

db.PbocJson.find({
_id: {
$type: "string"  //各种字段类型 如 int、long、decimal、double、bool、timestamp 类型为小写
}
})

 

统计总条数

db.PbocJson.find().count()

3、保存数组和更新数组操作

//保存一条语句
db.PbocJson.insert({ name:
'kad', tags: ['mongodb', 'database', 'NoSQL'], })

//追加数据数组,不论元素是否存在数组中,都追加
db.PbocJson.update({name : "kad"}, { $push : { tags : "mysql"}})
//追加数据数组,如存在则不追加,不存在则追加,可保证无重复数据
db.PbocJson.update({name : "kad"}, { $addToSet : { tags : "DB2"}})

//删除数组数据,删除开头或末尾元素
db.PbocJson.update({name : "kad"}, { $pop : { tags :-1}}) // -1表示开头元素 1表示末尾元素

//插入两条数据
db.PbocJson.insert(
{
_id: 3,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
})
;
db.PbocJson.insert(
{
_id: 4,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
})

//使用in查询插入的两条数据
db.PbocJson.find({_id:{$in:[3,4]}})
//使用pull更新数组数据 将fruits中的apples和orange删除,将vegetables中的carrorts删除
db.PbocJson.update( { }, //{} 无任何条件,表示所有元素,否则可以指定元素 如{_id:{$in:[3,4]}}
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
{ multi: true })

 

 

 

mongoDb支持存储过程、索引、游标、正则表达式。

posted @ 2018-08-24 13:14  黄柳  阅读(505)  评论(0编辑  收藏  举报