MongoDB四(插入文档)

一、插入文档

将数据插入MongoDB集合中,需要使用insert()或save()方法。

注:如果该集合不存在则直接创建该集合

使用格式为:db.collection_name.insert(document)
范例:

db.mycol.insert({
_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
})

_id 是一个 12 字节长的 16 进制数,这 12 个字节的分配如下:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

二、 查询文档

  • 想要在MongoDB中查询文档,使用find()方法
    使用的格式为:db.collection_name.find()
    范例:
db.mycol.find()
{ "_id" : ObjectId("59794d992a07cd4b99876032") }
{ "_id" : ObjectId("59794dcf2a07cd4b99876033"), "title" : "Mongo", "description" : "no sql database", "likes" : 100}
  • 格式化显示结果,使用的是pretty()方法
    使用格式为:db.collection_name.find().pretty()
    范例:
> db.mycol.find().pretty()
{ "_id" : ObjectId("59794d992a07cd4b99876032") }
{
        "_id" : ObjectId("59794dcf2a07cd4b99876033"),
        "title" : "Mongo",
        "description" : "no sql database",
        "likes" : 100
}

三、MongoDB中类似于WHERE子句的语句

语句

四、MongoDB中的AND条件

在find方法中,如果传入多个键,并用,分隔他们,那么MongoDB就会把它看成是AND条件。
使用格式:

db.mycol.find({key1:value1, key2:value2}).pretty()

五、 MongoDB中的OR条件

语法格式:

db.mycol.find(
  {
    $or: [
        {key1: value1}, {key2:value2}
     ]
  }
).pretty()

六、 结合使用AND与OR条件

范例:

db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
发布了31 篇原创文章 · 获赞 25 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/s_842499467/article/details/76209391