數據樣例
{ "_id" : ObjectId("5e67343f00850012ec08ad3e"), "river" : [ "長江", "黃河", "淮河" ] } { "_id" : ObjectId("5e67343f00850012ec08ad3f"), "river" : [ "長江", "松花江", "嘉陵江" ] }
一:普通包含查詢
def get_all(self):
# 查詢數組中包含長江的所有文檔 result_cursor = self.db["test_info"].find({"river":"長江"}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [{'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['長江', '黃河', '淮河']}, {'_id': ObjectId('5e67343f00850012ec08ad3f'), 'river': ['長江', '松花江', '嘉陵江']}]
二:$all 包含查詢
數據樣例
{ "_id" : ObjectId("5e67343f00850012ec08ad3e"), "river" : [ "長江", "黃河", "淮河" ] } { "_id" : ObjectId("5e67343f00850012ec08ad3f"), "river" : [ "長江", "松花江", "嘉陵江" ] } { "_id" : ObjectId("5e6737552a89d7c2fc0cd5d1"), "river" : [ "長江", "黃河", "黃浦江" ] }
需要查詢數組里面包含長江和黃河的所有文檔
def get_all(self): result_cursor = self.db["test_info"].find({"river":{"$all":["長江","黃河"]}}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [{'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['長江', '黃河', '淮河']}, {'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['長江', '黃河', '黃浦江']}]
普通查詢的 {"river":"長江"} 其實就相當於 {"river":{"$all":["長江"]}
三:指定位置(下標)查詢 數組名稱.index
要查詢數組最后一位元素是黃浦江的文檔
def get_all(self): result_cursor = self.db["test_info"].find({"river.2":"黃浦江"}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [{'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['長江', '黃河', '黃浦江']}]
四:指定長度查詢 $size
查詢數組長度為3的所有文檔
def get_all_size(self): result_cursor = self.db["test_info"].find({"river":{"$size":3}}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [{'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['長江', '黃河', '淮河']}, {'_id': ObjectId('5e67343f00850012ec08ad3f'), 'river': ['長江', '松花江', '嘉陵江']}, {'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['長江', '黃河', '黃浦江']}]
五:返回數組的一個子集 $slice find的第二個查詢參數
返回查詢結果數組里面的前兩個元素
def get_all_size(self): result_cursor = self.db["test_info"].find({},{"river":{"$slice":2}}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [{'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['長江', '黃河']}, {'_id': ObjectId('5e67343f00850012ec08ad3f'), 'river': ['長江', '松花江']}, {'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['長江', '黃河']}]
def get_all_size(self): result_cursor = self.db["test_info"].find({},{"river":{"$slice":-1}}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [ {'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['淮河']}, {'_id': ObjectId('5e67343f00850012ec08ad3f'), 'river': ['嘉陵江']}, {'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['黃浦江']}]
返回查詢結果數組里面的最后一個元素
$slice可以接受偏移量,跳過指定數量的元素,返回指定數量的元素
def get_all_size(self): result_cursor = self.db["test_info"].find({},{"river":{"$slice":[1,2]}}) temp = list() for result in result_cursor: temp.append(result) print(temp) return temp [ {'_id': ObjectId('5e67343f00850012ec08ad3e'), 'river': ['黃河', '淮河']}, {'_id': ObjectId('5e67343f00850012ec08ad3f'), 'river': ['松花江', '嘉陵江']}, {'_id': ObjectId('5e6737552a89d7c2fc0cd5d1'), 'river': ['黃河', '黃浦江']}]
跳過數組里面的第一個元素,返回跳過后的前兩個元素:如果跳過第一個元素后,剩下的元素不夠兩個,就返回剩下的所有元素
數據格式如下
{ "_id" : ObjectId("5e688d3a2a89d7c2fc0d64ee"), "t_id" : "1", "data" : [ { "time" : ISODate("2020-03-07T19:59:00.000Z"), "x" : "100" }, { "time" : ISODate("2020-03-08T19:59:00.000Z"), "x" : "200" }, { "time" : ISODate("2020-03-09T19:59:00.000Z"), "x" : "300" }, { "time" : ISODate("2020-03-10T19:59:00.000Z"), "x" : "400" }, { "time" : ISODate("2020-03-11T19:59:00.000Z"), "x" : "500" } ] }
數組里面的元素,返回指定時間段內的數據,返回 2020-03-07-2020-03-11之間的data數據
def get_list_time_range(self): if self.connect_result: s_time = datetime.datetime(2020,3,7,0,0,0) e_time = datetime.datetime(2020,3,11,23,59,59) match_dict = {"$match":{"t_id":"1"}} unwind_dict = {"$unwind":"$data"} project_dict = {"$project":{"_id":0,"data":1}} match_dict2 = {"$match":{"data.time":{"$gte":s_time,"$lte":e_time}}} result = self.db["test_info"].aggregate([match_dict,unwind_dict,project_dict,match_dict2]) temp_list = list() print(result) for info in result: info = info["data"] print(info) temp_list.append((info["x"],100)) print(temp_list)
結果
<pymongo.command_cursor.CommandCursor object at 0x0000000002FF3D88> {'time': datetime.datetime(2020, 3, 7, 19, 59), 'x': '100'} {'time': datetime.datetime(2020, 3, 8, 19, 59), 'x': '200'} {'time': datetime.datetime(2020, 3, 9, 19, 59), 'x': '300'} {'time': datetime.datetime(2020, 3, 10, 19, 59), 'x': '400'} {'time': datetime.datetime(2020, 3, 11, 19, 59), 'x': '500'} [('100', 100), ('200', 100), ('300', 100), ('400', 100), ('500', 100)]
六,數組插入數據
$push:將內容插入指定的數組里面,不論內容是否相同,不進行去重,均執行插入
# 數據樣式 { "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [] }
需求一:給 data_list插入三組一樣的數據
def push_method(self): result = self.db["test1"].update({"name":"a"},{"$push":{"data_list":{"city":"西安"}}}) print(result) # 結果 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
執行三次后的結果
{ "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [ { "city" : "西安" }, { "city" : "西安" }, { "city" : "西安" } ] }
結果可以看出,相同的三組數據都可以插入,那么怎么讓相同的數據,不能夠插入呢?
# 數據格式 { "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [] }
$addToSet:將內容插入指定數組,內容相同就不執行插入,去重
執行三次的打印結果
def add_to_set(self): result = self.db["test1"].update({"name": "a"}, {"$addToSet": {"data_list": {"city": "西安"}}}) print(result) # 結果 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True} {'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True} {'n': 1, 'nModified': 0, 'ok': 1.0, 'updatedExisting': True}
執行三次的數據樣式
/* 1 */ { "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [ { "city" : "西安" } ] }
$pushAll:版本4.0.10已經作廢,可使用 push代替,插入一組數據
# 數據樣式 { "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [] }
MongoDB shell version v4.0.10
報錯:
pymongo.errors.WriteError: Unknown modifier: $pushAll
def push_many_method(self): result = self.db["test1"].update({"name": "a"}, {"$push": {"data_list":[{"city": "西安"},{"city": "南京"}]}}) print(result) # 結果 {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}
/* 1 */ { "_id" : ObjectId("5e8eba932a89d7c2fc29ebb3"), "name" : "a", "data_list" : [ [ { "city" : "西安" }, { "city" : "南京" } ] ] }
可以看出,push也可以一次性,插入多組數據。
https://blog.csdn.net/oxgos/article/details/78837931
https://www.cnblogs.com/xuliuzai/p/10331524.html
# TODO