MongoDB database query (a)

1 MongoDB Introduction

MongoDB is a distributed file storage based database. Written by C ++ language. Designed to provide scalable, high-performance data storage solution for WEB applications.

MongoDB is a product with function between relational databases and non-relational databases, non-relational database functions among the richest and most like a relational database.

Recursive relationship in MongoDB :

  • One example of MongoDB may have a plurality of independent database (database), each database has its own set;
  • Collection (Collection) can be seen as a dynamic mode has (dynamic schema) of the table;
  • MongDB document is the basic unit of data, corresponding to a row in a relational database;
  • Each document has a special key "id", this is the only key in the collection of documents belongs.

Document key / value pairs are ordered: { "x": 1, "y": 2} and { "y": 2, "x": 1} are different.

FIG example by the following, we can more intuitive understanding of some concepts Mongo:

2 Python connection MongoDB

The main work is MongoDB query in the query window Ali cloud server, sometimes using the Python connection MongoDB query.

Python is connected Ali cloud MongoDB, first need to install the Python module pymongo, then based on the following operations:

from pymongo import MongoClient

client = MongoClient('mongodb://username:password@localhost:port/database')
db = client.database  # 这里为什么还要再加一次数据库名称?

# 或者
client = MongoClient('mongodb://localhost:port/database', username='username', password='password')

3 Mongo Date Type

Mongo can be seen in the time of storage type ISODate, such as "reqTime": "ISODate (" 2018-07-11T02: 12 is: 49.109Z ")" . This is due to the time in Mongo to UTC (Coordinated Universal Time) the type of storage, equivalent to GMT (Greenwich Mean time) time. And we are currently located +8 (Beijing time), so Mongo sets the current time minus 8, and then stored as GMT.

3.1 Mongo shell type Date

3.1.1 new Date (), and Date () Compare

# new Date() 返回当前的 Date 日期对象,mongo shell 使用 ISODate 来包装 Date 对象
db.test.insert( { mark: 1, mark_time: new Date() } )
# Date() 返回当前日期的字符串形式
db.test.insert( { mark: 2, mark_time: Date() } )
db.test.find()

# 返回结果
{ "_id" : ObjectId("5126e00939899c4cf3805f9b"), "mark" : 1, "mark_time" : ISODate("2019-06-05T03:03:37.312Z") }
{ "_id" : ObjectId("5126e00c39899c4cf3805f9c"), "mark" : 2, "mark_time" : "Wed Jun 05 2019 11:03:40 GMT+0800" }

We can pass to the new Date () builder or ISODate () functions that accept the following format:

  • new Date ( "YYYY-mm- dd") Returns ISODate specified date
  • a Date new new ( "YYYY-mm-ddTHH: the MM: SS") datetime client specifies the current time zone, and return in UTC ISODate specified datetime
  • new Date ( "YYYY-mm- ddTHH: MM: ssZ") specified in UTC datetime, and returns the UTC ISODate specified datetime
  • new Date (integer) specified from datetime (Jan 1,1970) since the Unix epoch is milliseconds, and returns ISODate examples

3.1.2 running instance of Ali cloud MongoDB query window

Example 1

db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': new Date("2019-06-05T00:00:00") } }
    },    
    
    {'$match': {'sceneNo': '800'}
    }
])

Example 2

db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': new Date("2019-06-05 00:00:00") } }
    },    
    
    {'$match': {'sceneNo': '800'}
    }
])

Example 3

db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': new Date("2019-06-05") } }
    },    
    
    {'$match': {'sceneNo': '800'}
    }
])

Example 4

db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': new Date("2019-06-05T00:00:00Z") } }
    },    
    
    {'$match': {'sceneNo': '800'}
    }
])

Example 5

db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': ISODate("2019-06-04T16:00:00.000Z")} }
    },
    
    {'$match': {'sceneNo': '800'}
    }
])

Example 6

# 图中显示时间为当前运行时间
db.arcVerify.aggregate([    
    {'$match': {'addTime': {'$gte': Date("2019-06-05 00:00:00.00")} }
    },
    
    {'$match': {'sceneNo': '800'}
    }
])

3.2 Python query date

3.2.1 Python Date Type

pyMongo 使用 datetime.datetime 对象来表示 MongoDB documents(文档) 中 dates 和 times。因为 MongoDB 假定 dates 和 times 是 UTC 形式的,所以我们要确保被写进数据库的时间可以反映 UTC。例如,下面的代码在 MongoDB 中存储当前 UTC date 和 time:

result = db.objects.insert_one( { "last_modified": datetime.datetime.utcnow() } )

使用 datetime.datetime.utcnow() 可以返回 UTC 中的 current time,而 datetime.datetime.now() 返回 current local time。避免如下操作:

result = db.objects.insert_one( { "last_modified": datetime.datetime.now() } )

在上面两个例子中,虽然两个文档都在同样的 local time 被存储,但是 last_modified 值是非常不同的。这可能对于读取它们的应用来说会有些混乱:

[doc['last_modified'] for doc in db.objects.find()]  

# 结果
[datetime.datetime(2019, 6, 7, 4, 23, 41, 582944),
 datetime.datetime(2019, 6, 7, 12, 23, 42, 727949)]

3.2.2 实例

查找 2019-06-06 日的数据

from datetime import datetime

date = '2019-06-06'
intdate = [int(i) for i in date.split("-")]
date1 = datetime(intdate[0], intdate[1], intdate[2]) - timedelta(hours=8)
date2 = datetime(intdate[0], intdate[1], intdate[2]) + timedelta(hours=16)

db.arcSceneRuleDetail.aggregate([
        {'$match':
            {'addTime': {"$gte": date1,
                         "$lt": date2}
            }
        },
        ...
])

# 或者 
db.arcSceneRuleDetail.aggregate([
        {'$match':
            {'addTime': {"$gte": datetime(2019, 6, 5, 16, 0),
                         "$lt": datetime(2019, 6, 6, 16, 0)}
            }
        },
        ...
])

参考资料

  1. MongoDB 概念解析

  2. Mongo日期类型

  3. mongoDB 文档 Date()

  4. PyMongo 3.8.0 documentation 中 Datetimes and Timezones

Guess you like

Origin www.cnblogs.com/shaocf/p/10953894.html