博客
关于我
MongoDB 文档的查询和插入操作
阅读量:753 次
发布时间:2019-03-23

本文共 1709 字,大约阅读时间需要 5 分钟。

MongoDB是文档型数据库,与传统的关系型数据库有着显著的不同,理解这些差异对于有效地使用MongoDB至关重要。文档结构类似于数据库中的row,每个文档由key/value对组成,key和value用冒号(:)分隔,多个key/value对用逗号(,)分隔。例如:

user = {  name: "sue",  age: 24}

MongoDB支持将文档存储在文档数组中,这对于批量插入和批量更新操作特别有用。例如:

userArray = [  { name: "sue", age: 24 },  { name: "joe", age: 25 },  { name: "pei", age: 32 }];

在开始操作前,可以使用use test命令切换到测试数据库,以避免对生产环境造成影响。

插入操作

MongoDB提供了几种插入方法:

  • 单个文档插入:使用db.collection.insert()db.collection.insertOne()或直接传递文档:

    user = { name: "test1", age: 22 };db.users.insert(user);db.users.insert({ name: "test1", age: 22 });db.users.insertOne({ name: "test1", age: 22 });
  • 批量插入文档:使用db.collection.insertMany()来插入文档数组:

    db.users.insert([user1, user2, user3]);db.users.insertMany([user1, user2, user3]);
  • 查找操作

    查询操作是MongoDB中最常用的操作之一,基础的查询语法如下:

    db.collection.find(  
    ,
    );

    Query Filter是用来过滤文档的条件,而Projection用于指定要返回的字段集合,默认是返回所有字段。如果不指定_id字段的投影,默认会包含_id。

    常见的Query运算符

  • 等式匹配

    db.users.find({ age: 21 });db.users.find({ age: { $eq: 21 } });
  • 不等式匹配

    db.users.find({ age: { $ne: 21 } });
  • 范围匹配

    db.users.find({ age: { $lt: 22 } });db.users.find({ age: { $gt: 22 } });
  • 逻辑运算符

    $or、$and:db.users.find({ $or: [{ age: 21 }, { age: 22 }] });
  • 集合匹配

    db.users.find({ age: { $in: [21, 22] } });
  • 集合不匹配

    db.users.find({ age: { $nin: [21, 22] } });
  • Projection(投影)

    为了提高查询效率,可以通过Projection指定返回的字段:

    db.users.find({ age: 21 }, { name: 1, _id: 0 });

    这将返回匹配的所有文档,只包含指定的字段。去除_id字段可以通过设定projection选项来实现。

    Cursor And Iteration

    db.collection.find()返回一个Cursor,用户可以通过以下方法迭代Cursor:

  • 使用var声明Cursor:

    var us = db.users.find();
  • 手动迭代:

    while (us.hasNext()) {  print(tojson(us.next()));}
  • 使用forEach

    db.users.find().forEach(function (doc) {  print(tojson(doc));});
  • 通过明确声明Cursor,可以避免MongoDB自动迭代,默认会显示前20个文档,用户应谨慎利用.find()方法。

    转载地址:http://zsfzk.baihongyu.com/

    你可能感兴趣的文章
    MySQL中你必须知道的10件事,1.5万字!
    查看>>
    MySQL中使用IN()查询到底走不走索引?
    查看>>
    Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
    查看>>
    MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
    查看>>
    mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
    查看>>
    mysql中出现Unit mysql.service could not be found 的解决方法
    查看>>
    mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
    查看>>
    Mysql中各类锁的机制图文详细解析(全)
    查看>>
    MySQL中地理位置数据扩展geometry的使用心得
    查看>>
    Mysql中存储引擎简介、修改、查询、选择
    查看>>
    Mysql中存储过程、存储函数、自定义函数、变量、流程控制语句、光标/游标、定义条件和处理程序的使用示例
    查看>>
    mysql中实现rownum,对结果进行排序
    查看>>
    mysql中对于数据库的基本操作
    查看>>
    Mysql中常用函数的使用示例
    查看>>
    MySql中怎样使用case-when实现判断查询结果返回
    查看>>
    Mysql中怎样使用update更新某列的数据减去指定值
    查看>>
    Mysql中怎样设置指定ip远程访问连接
    查看>>
    mysql中数据表的基本操作很难嘛,由这个实验来带你从头走一遍
    查看>>
    Mysql中文乱码问题完美解决方案
    查看>>
    mysql中的 +号 和 CONCAT(str1,str2,...)
    查看>>