I had some data sample like these:
[
{
"_id": 1,
"host": "host1",
"type": "type1",
"data": [
{
"t": 10000,
"v": 90
},
{
"t": 10001,
"v": 94
},
]
},
{
"_id": 2,
"host": "host1",
"type": "type1",
"data": [
{
"t": 10000,
"v": 99
},
{
"t": 10001,
"v": 93
},
]
},
{
"_id": 3,
"host": "host1",
"type": "type1",
"data": [
{
"t": 10000,
"v": 94
},
{
"t": 10001,
"v": 100
},
]
}]
my query is:
my_filter = {'host': 'host1', 'type': 'type1', 'data': {'$elemMatch': {'t': 10000}}}
projection = {'host': 1, 'type': 1, 'data': {'$elemMatch': {'t': 10000}}}
sort_key = 'data.0.v'
rs = db.find(my_filter, projection).sort(sort_key, 1)
rs = list(rs)
for v in rs:
print(v["data"][0]['v'])
but output like that sort doest work:
98
98
98
96
100
98
98
Notice:
- now use: Python==3.6.9, pymongo==3.10.1, MongoDB==4.2.6
- the length of documents is 10000, the length of nested array is 1440
- I only need data that meet the conditions in Nested Array, not all, because it might be a large array
- I need sort data, but I can't change the write order
- I also used $aggregate, but when data is large, it performance is bad, so I hope do some operation with find()
$aggregate like these:
rs = db.aggregate([
{"$match": {'host': 'host1', 'type': 'type1', 'data': {'$elemMatch': {'t': 10000}}}},
{"$project": {'host': 1, 'type': 1,
'data': {"$filter": {
"input": "$data",
"as": "data",
"cond": {"$eq": ["$$data.t", 10000]}}
}
}},
{"$sort": {'data.0.v': 1}}])
sorry for my poor English, but is here a good solution?