import itertools
import operator
def monotone_increasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.le, pairs))
def monotone_decreasing(lst):
pairs = zip(lst, lst[1:])
return all(itertools.starmap(operator.ge, pairs))
def monotone(lst):
return monotone_increasing(lst) or monotone_decreasing(lst)
Этот подход равен O(N)
в длине списка.
//Employee Documents
/* 1 */
{
"_id" : ObjectId("5c41aaa91d0b034e617effc0"),
"emp_id" : 1
}
/* 2 */
{
"_id" : ObjectId("5c41aaec1d0b034e617f0001"),
"emp_id" : 2
}
/* 3 */
{
"_id" : ObjectId("5c41aaf31d0b034e617f0009"),
"emp_id" : 3
}
//Salary Documents:
{
"_id" : ObjectId("5c41aac01d0b034e617effd4"),
"emp_id" : 1,
"salary" : 1000
}
**//Query**
db.employee.aggregate([
{
$lookup:{
from: "salary",
localField: "emp_id", //reference of employee collection
foreignField: "emp_id", //reference of salary collection
as: "sal"
}
},{
$unwind: {
path: "$sal",
preserveNullAndEmptyArrays: true //will return null if salary does not exist
}
},{
$project:{
emp_id: 1,
salary: { $ifNull: [ "$sal.salary", 0 ] } //will set to 0 if salary does not exist
}
}]);
//Output
/* 1 */
{
"_id" : ObjectId("5c41aaa91d0b034e617effc0"),
"emp_id" : 1,
"salary" : 1000
}
/* 2 */
{
"_id" : ObjectId("5c41aaec1d0b034e617f0001"),
"emp_id" : 2,
"salary" : 0.0
}
/* 3 */
{
"_id" : ObjectId("5c41aaf31d0b034e617f0009"),
"emp_id" : 3,
"salary" : 0.0
}