您现在的位置是:首页 >其他 >MongoDB教程-3网站首页其他
MongoDB教程-3
insert()方法
要将数据插入MongoDB集合,需要使用MongoDB的insert()或save()方法。
语法
insert()命令的基本语法如下−
>db.COLLECTION_NAME.insert(document)
例子:
> db.users.insert({ ... _id : ObjectId("507f191e810c19729de860ea"), ... title: "MongoDB Overview", ... description: "MongoDB is no sql database", ... by: "tutorials point", ... url: "http://www.tutorialspoint.com", ... tags: ['mongodb', 'database', 'NoSQL'], ... likes: 100 ... }) WriteResult({ "nInserted" : 1 }) >
这里mycol是我们的集合名称,如前一章中所创建的。如果数据库中不存在集合,MongoDB将创建此集合,然后将文档插入其中。
在插入的文档中,如果我们没有指定_id参数,那么MongoDB将为此文档分配一个唯一的ObjectId。
_id是集合中每个文档唯一的12字节十六进制数。12个字节划分如下−
_id: ObjectId(4 bytes 时间戳, 3 bytes 机器id, 2 bytes 进程id, 3 bytes 自增)
您还可以将文档数组传递到insert()方法中,如下所示:。
> db.createCollection("post")
> db.post.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
要插入文档,还可以使用db.post.save(document)。如果不在文档中指定_id,则save()方法的工作方式与insert()方法相同。如果指定了_id,那么它将替换save()方法中指定的包含_id的文档的整个数据。
insertOne()方法
如果只需要在集合中插入一个文档,则可以使用此方法。
语法
insert()命令的基本语法如下−
>db.COLLECTION_NAME.insertOne(document)
实例
以下示例创建一个名为empDetails的新集合,并使用insertOne()方法插入文档。
> db.createCollection("empDetails") { "ok" : 1 }
> db.empDetails.insertOne( { First_Name: "Radhika", Last_Name: "Sharma", Date_Of_Birth: "1995-09-26", e_mail: "radhika_sharma.123@gmail.com", phone: "9848022338" }) { "acknowledged" : true, "insertedId" : ObjectId("5dd62b4070fb13eec3963bea") } >
insertMany()方法
可以使用insertMany()方法插入多个文档。您需要向该方法传递一组文档。
实例
以下示例使用insertMany()方法将三个不同的文档插入empDetails集合。
> db.empDetails.insertMany( [ { First_Name: "Radhika", Last_Name: "Sharma", Date_Of_Birth: "1995-09-26", e_mail: "radhika_sharma.123@gmail.com", phone: "9000012345" }, { First_Name: "Rachel", Last_Name: "Christopher", Date_Of_Birth: "1990-02-16", e_mail: "Rachel_Christopher.123@gmail.com", phone: "9000054321" }, { First_Name: "Fathima", Last_Name: "Sheik", Date_Of_Birth: "1990-02-16", e_mail: "Fathima_Sheik.123@gmail.com", phone: "9000054321" } ] ) { "acknowledged" : true, "insertedIds" : [ ObjectId("5dd631f270fb13eec3963bed"), ObjectId("5dd631f270fb13eec3963bee"), ObjectId("5dd631f270fb13eec3963bef") ] } >
find()方法
要从MongoDB集合中查询数据,需要使用MongoDB的find()方法。
语法
find()方法的基本语法如下−
>db.COLLECTION_NAME.find()
find()方法将以非结构化方式显示所有文档。
实例
假设我们创建了一个名为mycol的集合作为−
> use sampleDB switched to db sampleDB > db.createCollection("mycol") { "ok" : 1 } >
并使用insert()方法在其中插入了3个文档,如下所示-
> db.mycol.insert([
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "tutorials point",
url: "http://www.tutorialspoint.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])
以下方法检索集合中的所有文档−
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>
prety()方法
要以格式化的方式显示结果,可以使用pretty()方法。
语法
>db.COLLECTION_NAME.find().pretty()
实例
以下示例从名为mycol的集合中检索所有文档,并以易于阅读的格式排列它们。
> db.mycol.find().pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
"title" : "NoSQL Database",
"description" : "NoSQL database doesn't have tables",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 20,
"comments" : [
{
"user" : "user1",
"message" : "My first comment",
"dateCreated" : ISODate("2013-12-09T21:05:00Z"),
"like" : 0
}
]
}
findOne()方法
除了find()方法之外,还有findOne()方法,它只返回一个文档。
语法
>db.COLLECTIONNAME.findOne()
实例
以下示例检索标题为MongoDB Overview的文档。
> db.mycol.findOne({title: "MongoDB Overview"})
{
"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
MongoDB中的RDBMS Where子句等价物
要根据某些条件查询文档,可以使用以下操作。
操作 | 语法 | 例子 | RDBMS例子 |
---|---|---|---|
等于 | {<key>:{$eg;<value>}} | db.mycol.find({"by":"tutorials point"}).pretty() | where by = 'tutorials point' |
小于 | {<key>:{$lt:<value>}} | db.mycol.find({"likes":{$lt:50}}).pretty() | where likes < 50 |
小于等于 | {<key>:{$lte:<value>}} | db.mycol.find({"likes":{$lte:50}}).pretty() | where likes <= 50 |
大于 | {<key>:{$gt:<value>}} | db.mycol.find({"likes":{$gt:50}}).pretty() | where likes > 50 |
大于等于 | {<key>:{$gte:<value>}} | db.mycol.find({"likes":{$gte:50}}).pretty() | where likes >= 50 |
不等于 | {<key>:{$ne:<value>}} | db.mycol.find({"likes":{$ne:50}}).pretty() | where likes != 50 |
包含in | {<key>:{$in:[<value1>, <value2>,……<valueN>]}} | db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty() | Where name matches any of the value in :["Raj", "Ram", "Raghu"] |
不包含 | {<key>:{$nin:<value>}} | db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty() | Where name values is not in the array :["Ramu", "Raghav"] or, doesn’t exist at all |
MongoDB中的AND
语法
要根据AND条件查询文档,需要使用$AND关键字。以下是AND−的基本语法
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
实例
以下示例将显示由“tutorialspoint”编写的所有教程,其标题为“MongoDB Overview”。
> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 } >
对于上面给出的示例,等价的where子句将是“where by=”tutorials point“AND title=”MongoDB Overview“”。可以在find子句中传递任意数量的键、值对。
MongoDB中的OR
语法
要根据OR条件查询文档,需要使用$OR关键字。以下是OR−的基本语法
>db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
实例
以下示例将显示由“tutorialspoint”编写的或标题为“MongoDB Overview”的所有教程。
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "tutorials point", "url": "http://www.tutorialspoint.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
一起使用AND和OR
实例
下面的示例将显示点赞数超过10的文档,其标题为“MongoDB Overview”或“tutorials point”。等效的SQL where子句是“where likes>10 AND(by=“tutorials point”或title=“MongoDB Overview”)”
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is no sql database", "by": "tutorials point", "url": "http://www.tutorialspoint.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
MongoDB中的NOR
语法
要基于NOT条件查询文档,需要使用$NOT关键字。以下是NOT−的基本语法:
>db.COLLECTION_NAME.find( { $not: [ {key1: value1}, {key2:value2} ] } )
实例
假设我们在集合empDetails中插入了3个文档,如下所示-
db.empDetails.insertMany( [ { First_Name: "Radhika", Last_Name: "Sharma", Age: "26", e_mail: "radhika_sharma.123@gmail.com", phone: "9000012345" }, { First_Name: "Rachel", Last_Name: "Christopher", Age: "27", e_mail: "Rachel_Christopher.123@gmail.com", phone: "9000054321" }, { First_Name: "Fathima", Last_Name: "Sheik", Age: "24", e_mail: "Fathima_Sheik.123@gmail.com", phone: "9000054321" } ] )
以下示例将检索名不是“Radhika”、姓不是“Christopher”的文档
> db.empDetails.find(
{
$nor:[
40
{"First_Name": "Radhika"},
{"Last_Name": "Christopher"}
]
}
).pretty()
{
"_id" : ObjectId("5dd631f270fb13eec3963bef"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "Fathima_Sheik.123@gmail.com",
"phone" : "9000054321"
}
不在MongoDB中
语法
要根据NOT条件查询文档,需要使用$NOT关键字。以下是NOT−的基本语法
>db.COLLECTION_NAME.find( { $NOT: [ {key1: value1}, {key2:value2} ] } ).pretty()
实例
以下示例将检索年龄不超过25岁的文档
> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } ) { "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" }
MongoDB的update()和save()方法用于将文档更新到集合中。update()方法更新现有文档中的值,而save()方法用save()中传递的文档替换现有文档。
MongoDB Update()方法
update()方法更新现有文档中的值。
语法
update()方法的基本语法如下−
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
实例
考虑mycol集合具有以下数据。
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
以下示例将为标题为“MongoDB概述”的文档设置新标题“new MongoDB Tutorial”。
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) >db.mycol.find() { "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"} >
默认情况下,MongoDB将只更新一个文档。要更新多个文档,需要将参数“multi”设置为true。
>db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}},{multi:true})
MongoDB Save()方法
save()方法用save()中传递的新文档替换现有文档。
语法
MongoDB save()方法的基本语法如下−
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
实例
以下示例将用_id“5983548781331adf45ec5”替换文档。
>db.mycol.save(
{
"_id" : ObjectId("507f191e810c19729de860ea"),
"title":"Tutorials Point New Topic",
"by":"Tutorials Point"
}
)
WriteResult({
"nMatched" : 0,
"nUpserted" : 1,
"nModified" : 0,
"_id" : ObjectId("507f191e810c19729de860ea")
})
>db.mycol.find()
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point New Topic",
"by":"Tutorials Point"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"NoSQL Overview"}
{ "_id" : ObjectId("507f191e810c19729de860e6"), "title":"Tutorials Point Overview"}
>
MongoDB findOneAndUpdate()方法
findOneAndUpdate()方法更新现有文档中的值。
语法
findOneAndUpdate()方法的基本语法如下−
>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA)
实例
假设我们创建了一个名为empDetails的集合,并在其中插入了三个文档,如下所示-
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "radhika_sharma.123@gmail.com",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "Rachel_Christopher.123@gmail.com",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "Fathima_Sheik.123@gmail.com",
phone: "9000054321"
}
]
)
以下示例更新名为“Radhika”的文档的年龄和电子邮件值。
> db.empDetails.findOneAndUpdate(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{
"_id" : ObjectId("5dd6636870fb13eec3963bf5"),
"First_Name" : "Radhika",
"Last_Name" : "Sharma",
"Age" : "30",
"e_mail" : "radhika_newemail@gmail.com",
"phone" : "9000012345"
}
MongoDB updateOne()方法
此方法更新与给定筛选器匹配的单个文档。
语法
updateOne()方法的基本语法如下−
>db.COLLECTION_NAME.updateOne(<filter>, <update>)
例子
> db.empDetails.updateOne(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: 'radhika_newemail@gmail.com'}}
)
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 0 }
>
MongoDB updateMany()方法
updateMany()方法更新与给定筛选器匹配的所有文档。
语法
updateMany()方法的基本语法如下−
>db.COLLECTION_NAME.update(<filter>, <update>)
例子
> db.empDetails.updateMany( {Age:{ $gt: "25" }}, { $set: { Age: '00'}} ) { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
如果使用find方法检索文档内容,则可以看到更新的值,如下所示−
> db.empDetails.find()
{ "_id" : ObjectId("5dd6636870fb13eec3963bf5"), "First_Name" : "Radhika", "Last_Name" : "Sharma", "Age" : "00", "e_mail" : "radhika_newemail@gmail.com", "phone" : "9000012345" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf6"), "First_Name" : "Rachel", "Last_Name" : "Christopher", "Age" : "00", "e_mail" : "Rachel_Christopher.123@gmail.com", "phone" : "9000054321" }
{ "_id" : ObjectId("5dd6636870fb13eec3963bf7"), "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "Fathima_Sheik.123@gmail.com", "phone" : "9000054321" }
>