MongoDB插入数据与等值查询

本文介绍了MongoDB如何切换数据库、插入数据到集合以及执行等值查询。在MongoDB中,如果数据库或集合不存在,会在首次插入数据时自动创建。插入数据的方法包括insertOne和insertMany。等值查询则利用find方法,可以按条件查找匹配的文档,如按属性值、数组内容等进行筛选。此外,还展示了如何通过投影指定查询结果返回的字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MongoDB插入数据与等值查询

切换数据库

切换数据库时,无需保证目标数据库已经存在。

//显示当前数据库
db
//切换数据库
use testdb

如果上面的testdb不存在,在首次向testdb中插入数据或者创建collection时,MongoDB会自动创建testdb。

插入数据

MongoDB将文档数据存储在collection中,collection类似于关系型数据库中的table

查看数据库中已有的Collections信息:

// 查看已有的Collections详细信息
db.getCollectionInfos() 
// 查看已有的Collections名称
db.getCollectionNames() 

如果某个collection不存在,在首次向其中插入数据时,MongoDB会自动创建该collection。

通过db.collection.insertOne()方法向名为inventory的collection中插入一条记录:

db.inventory.insertOne(
   { item: "magazine", qty: 32, status: "B", size: { h: 35, w: 20, uom: "cm" }, tags: [ "black" ] }
);

通过db.collection.insertMany()方法向名为inventory的collection中插入多条记录:

db.inventory.insertMany([
   { item: "journal", qty: 25, status: "A", size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "notebook", qty: 50, status: "A", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
   { item: "paper", qty: 10, status: "D", size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
   { item: "planner", qty: 0, status: "D", size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
   { item: "postcard", qty: 45, status: "A", size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);

// MongoDB adds an _id field with an ObjectId value if the field is not present in the document

等值查询

使用db.collection.find()来查询某个collection中所有或者特定的记录。

查询collection中的所有记录:

db.inventory.find({})
//使用pretty方法来美化查询输出
db.inventory.find({}).pretty()

查询匹配某个属性的所有记录:

//查询status值为D的所有记录
db.inventory.find( { status: "D" } );
//查询qty值为0的所有记录
db.inventory.find( { qty: 0 } );
//查询status值为D、且qty值为0的所有记录
db.inventory.find( { qty: 0, status: "D" } );

//查询sizes属性的uom子属性值为in的所有记录
db.inventory.find( { "size.uom": "in" } )
//查询sizes属性等于给定内容的所有记录
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

当键值为数组时,等值查询同时考虑内容匹配和顺序匹配。且以下两种查询方式意义不同:

db.inventory.find( { tags: "red" } )

表示查询tags对应数组中包含"red"元素的所有记录。

db.inventory.find( { tags: [ "red", "blank" ] } )

表示查询tags对应数组为[ "red", "blank" ]的所有记录。如果某条记录的tags对应数组为[ "blank", "red" ],也会被包含在查询结果集中。

对于查询的结果,可以通过db.collection.find(<query document>, <projection document>)方法指定仅输出部分内容,其中1表示输出内容,0表示隐藏内容。

db.inventory.find( { }, { item: 1, status: 1 } );

表示只输出所有记录的_iditemstatus属性(_id默认会输出)。

db.inventory.find( {}, { _id: 0, item: 1, status: 1 } );

表示只输出所有记录的itemstatus属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GottdesKrieges

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值