MongoDB - 文档基本操作(第一部分)

MongoDB - 文档基本操作(第一部分)

💡 原文英文,约500词,阅读约需2分钟。
📝

内容提要

本文介绍了MongoDB的基本文档操作,包括创建集合、插入、查询和删除数据。示例展示了条件查询、正则表达式查询和多条件查询的使用方法,并比较了MongoDB与关系数据库的查询语法,提供了提取字段、排序、限制返回记录和跳过记录的技巧。

🎯

关键要点

  • 创建集合的命令为 db.createCollection("posts");
  • 插入数据的示例包括 db.posts.insert({ title: "My First Blog", content: "Started writing blog, so excited." });
  • 使用循环插入多条数据的示例为 for(var i = 3; i <=10; i++ ) { db.posts.insert({ title: "My " + i + "th Blog" }); }
  • 查询数据的基本命令为 db.posts.find();
  • 条件查询示例包括 db.posts.find({"tag": "game"}); 和 db.posts.find({"rank": {$gte: 4}});
  • 正则表达式查询示例为 db.posts.find({"title": /u/});
  • 多条件查询示例为 db.posts.find({"title": /u/, "rank":{$gte:5} });
  • MongoDB与关系数据库的查询语法比较,包括相等、小于、大于等操作符的使用。
  • 提取字段的示例为 db.posts.find({}, {title:true, rank:1});
  • 排序、限制返回记录和跳过记录的命令示例包括 db.posts.find({}, {_id:0}).sort({rank:1}); 和 db.posts.find({}, {_id:0}).skip(3).limit(3);

延伸问答

如何在MongoDB中创建一个集合?

使用命令 db.createCollection('posts');

MongoDB中如何插入多条数据?

可以使用循环,例如 for(var i = 3; i <= 10; i++) { db.posts.insert({ title: 'My ' + i + 'th Blog' }); }。

MongoDB的基本查询命令是什么?

基本查询命令为 db.posts.find();

如何在MongoDB中进行条件查询?

可以使用 db.posts.find({'tag': 'game'}); 或 db.posts.find({'rank': {$gte: 4}});。

MongoDB与关系数据库的查询语法有什么不同?

MongoDB使用类似于 db.col.find({ 'by': 'test' }) 的语法,而关系数据库使用 where by = 'test' 的语法。

如何在MongoDB中提取特定字段?

可以使用 db.posts.find({}, {title: true, rank: 1}); 来提取指定字段。

➡️

继续阅读