本文共 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。
等式匹配:
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指定返回的字段:
db.users.find({ age: 21 }, { name: 1, _id: 0 });
这将返回匹配的所有文档,只包含指定的字段。去除_id字段可以通过设定projection选项来实现。
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/