注册

MongoDB的基础查询和索引操作方法总结

MongoDB是一种文档型数据库,它的查询操作和索引操作是使用得非常频繁的操作。本文将总结MongoDB的基础查询和索引操作方法。

基础查询方法

查询单个文档

语法

db.collectionName.findOne(query, projection)

参数含义

  • query:查询条件,可以是任意的查询表达式。
  • projection:可选参数,用来指定返回的文档中包含或不包含哪些字段。

示例说明

假设有一个名为student的集合,其中有如下文档:

{
    "_id": 1,
    "name": "张三",
    "age": 20,
    "sex": "男",
    "score": [80, 90, 70]
},
{
    "_id": 2,
    "name": "李四",
    "age": 21,
    "sex": "女",
    "score": [90, 85, 75]
}

查询_id为1的文档,返回所有字段:

db.student.findOne({_id: 1})

查询_id为1的文档,只返回nameage两个字段:

db.student.findOne({_id: 1}, {name: 1, age: 1, _id: 0})

查询多个文档

语法

db.collectionName.find(query, projection)

参数含义

  • query:查询条件,可以是任意的查询表达式。
  • projection:可选参数,用来指定返回的文档中包含或不包含哪些字段。

示例说明

假设有一个名为student的集合,其中有如下文档:

{
    "_id": 1,
    "name": "张三",
    "age": 20,
    "sex": "男",
    "score": [80, 90, 70]
},
{
    "_id": 2,
    "name": "李四",
    "age": 21,
    "sex": "女",
    "score": [90, 85, 75]
},
{
    "_id": 3,
    "name": "王五",
    "age": 19,
    "sex": "男",
    "score": [85, 80, 90]
}

查询所有年龄大于等于20岁的学生:

db.student.find({age: {$gte: 20}})

查询所有学生的nameage两个字段:

db.student.find({}, {name: 1, age: 1, _id: 0})

索引操作方法

创建索引

语法

db.collectionName.createIndex(keys, options)

参数含义

  • keys:用于创建索引的字段或字段组合,可以是一个包含多个字段的对象,也可以是一个包含每个字段键名和键值的数组。
  • options:可选参数,用于指定索引的额外信息,如索引的名称、唯一性等属性。

示例说明

假设有一个名为student的集合,其中有如下文档:

{
    "_id": 1,
    "name": "张三",
    "age": 20,
    "sex": "男",
    "score": [80, 90, 70]
},
{
    "_id": 2,
    "name": "李四",
    "age": 21,
    "sex": "女",
    "score": [90, 85, 75]
},
{
    "_id": 3,
    "name": "王五",
    "age": 19,
    "sex": "男",
    "score": [85, 80, 90]
}

name字段上创建普通索引:

db.student.createIndex({name: 1})

sexscore字段上创建联合索引:

db.student.createIndex({sex: 1, score: -1})

删除索引

语法

db.collectionName.dropIndex(index)

参数含义

  • index:要删除的索引对象或名称。

示例说明

删除name字段上的索引:

db.student.dropIndex({name: 1})

删除名为sex_1_score_-1的联合索引:

db.student.dropIndex("sex_1_score_-1")

总结

本文梳理了MongoDB的基础查询和索引操作方法,包括查询单个文档、查询多个文档、创建索引和删除索引。这些基本操作是使用MongoDB时必须掌握的基础内容,希望能对读者有所帮助。