本博客将列举一些常用的MongoDB操作,方便平时使用时快速查询,如find, count, 大于小于不等, select distinct, groupby等
// greater than : field > value
db.collection.find({ "field" : { $gt: value } } );
// less than : field < value
db.collection.find({ "field" : { $lt: value } } );
// greater than or equal to : field >= value
db.collection.find({ "field" : { $gte: value } } );
// less than or equal to : field <= value
db.collection.find({ "field" : { $lte: value } } );
// not equal: field != value
db.collection.find( { "field" : { $ne : value } } );
也可以合并在一条语句内:
// value1 < field < value
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );
db.collection.find( { "field" : { $in : array } } );
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
$exists用来判断一个元素(field)是否存在:
db.things.find( { a : { $exists : true } } );
db.things.find( { a : { $exists : false } } );
db.postings.find( { "author.name" : "joe" } );
注意用法是author.name
db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
如果我们要查询 authors name 是Jane的, 我们可以这样:
db.blog.findOne({"author.name" : "Jane"})
如果不用点,那就需要用下面这句才能匹配:
db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
$size是匹配数组内的元素数量的,如有一个对象:{a:[“foo”]},他只有一个元素:
下面的语句就可以匹配:
db.things.find( { a : { $size: 1 } } );
all和in类似,但是他需要匹配条件内所有的值:
如有一个对象:
{ a: [ 1, 2, 3 ] } 下面这个条件是可以匹配的:
db.things.find( { a: { $all: [ 2, 3 ] } } ); 但是下面这个条件就不行了:
db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
mongo支持正则表达式,如:
// 后面的i的意思是区分大小写
db.customers.find( { name : /acme.*corp/i } );
举例:可以用于复制collection
db.test(复制源表).find().forEach(function(x){
db.target(目的表).insert(x);
})
db.person.createIndex( {age: 1} )
上述语句针对age创建了单字段索引,其能加速对age字段的各种查询请求,是最常见的索引形式,MongoDB默认创建的id索引也是这种类型。
{age: 1} 代表升序索引,也可以通过{age: -1}来指定降序索引,对于单字段索引,升序/降序效果是一样的。
复合索引是Single Field Index的升级版本,它针对多个字段联合创建索引,先按第一个字段排序,第一个字段相同的文档按第二个字段排序,依次类推,如下针对age, name这2个字段创建一个复合索引。
db.person.createIndex( {age: 1, name: 1} )
当索引的字段为数组时,创建出的索引称为多key索引,多key索引会为数组的每个元素建立一条索引,比如person表加入一个habbit字段(数组)用于描述兴趣爱好,需要查询有相同兴趣爱好的人就可以利用habbit字段的多key索引。
{"name" : "jack", "age" : 19, habbit: ["football, runnning"]}
db.person.createIndex( {habbit: 1} ) // 自动创建多key索引
db.person.find( {habbit: "football"} )
mongo-9552:PRIMARY> db.person.getIndexes() // 查询集合的索引信息
[
{
"ns" : "test.person", // 集合名
"v" : 1, // 索引版本
"key" : { // 索引的字段及排序方向
"_id" : 1 // 根据_id字段升序索引
},
"name" : "_id_" // 索引的名称
}
]