美文网首页mongodb
mongo基本查询

mongo基本查询

作者: freedom117 | 来源:发表于2022-04-27 19:47 被阅读0次

1、基本查询

db.movies.find( { "year" : 1975 } ) //单条件查询
db.movies.find( { "year" : 1989, "title" : "Batman" } ) //多条件and查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } ) // and的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) //多条件or查询
db.movies.find( { "title" : /^B/} ) //按正则表达式查找

2.数组查询

db.movies.insertOne( {
"title" : "Raiders of the Lost Ark",
"filming_locations" : [ 
{ "city" : "Los Angeles", "state" : "CA", "country" : "USA" }, 
{ "city" : "Rome", "state" : "Lazio", "country" : "Italy" },
{ "city" : "Florence", "state" : "SC", "country" : "USA" }
] 
})
//遍历数组
db.movies.find({"filming_locations.city": "Rome"})
// 使用 $elemMatch,它表示必须是同一个数组中的子对象满足多个条件and
db.getCollection('movies').find({
"filming_locations": {
$elemMatch:{"city":"Rome", "country": "USA"}
}
})

3.控制 find 返回的字段

_id字段必须明确指明不返回,否则默认返回,只会返回title字段

db.movies.find({"category": "action"},{"_id":0, title:1})

4.删除

db.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
db.testcol.remove( { } ) // 删除所有记录
db.testcol.remove() //报错

5.更新

1、基本更新

db.fruit.insertMany([
{name: "apple"},
{name: "pear"},
{name: "orange"}
])
//updateMany更新多条
//updateOne更新一条
db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})

2、更新数组
push: 增加一个对象到数组底部 ●pushAll: 增加多个对象到数组底部
pop: 从数组底部删除一个对象 ●pull: 如果匹配指定的值,从数组中删除相应的对象
pullAll: 如果匹配任意的值,从数据中删除相应的对象 ●addToSet: 如果不存在则增加一个值到数组
3、使用 drop 删除集
● 使用 db.<集合>.drop() 来删除一个集合
● 集合中的全部文档都会被删除
● 集合相关的索引也会被删除

db.colToBeDropped.drop()

3、删除数据库

use tempDB
db.dropDatabase()

相关文章

网友评论

    本文标题:mongo基本查询

    本文链接:https://www.haomeiwen.com/subject/kjasrltx.html