O operador $lte retorna true quando o primeiro valor é menor ou igual ao segundo. Ele é útil para validações de limite em pipelines.
Exemplo
{ "_id" : 1, "a" : 250, "b" : 250 }
{ "_id" : 2, "a" : 300, "b" : 250 }
{ "_id" : 3, "a" : 250, "b" : 300 }
db.data.aggregate([ { $match: { _id: { $in: [1, 2, 3] } } }, { $project: { _id: 0, a: 1, b: 1, result: { $lte: ["$a", "$b"] } } } ])
Resultado:
{ "a" : 250, "b" : 250, "result" : true }
{ "a" : 300, "b" : 250, "result" : false }
{ "a" : 250, "b" : 300, "result" : true }
Comparação de tipos
O operador considera valor e tipo BSON.
{ "_id" : 4, "a" : 250, "b" : "250" }
{ "_id" : 5, "a" : "250", "b" : 250 }
{ "_id" : 6, "a" : 250, "b" : NumberDecimal("250") }
{ "_id" : 7, "a" : NumberDecimal("250"), "b" : 250 }
{ "_id" : 8, "a" : NumberDecimal("250"), "b" : NumberDecimal("250.00") }
{ "_id" : 9, "a" : NumberDecimal("250.00"), "b" : NumberDecimal("250") }
{ "_id" : 10, "a" : "2022-01-03T23:30:15.100Z", "b" : ISODate("2021-01-03T23:30:15.100Z") }
{ "_id" : 11, "a" : ISODate("2021-01-03T23:30:15.100Z"), "b" : "2021-01-03T23:30:15.100Z" }
db.data.aggregate([ { $match: { _id: { $in: [4, 5, 6, 7, 8, 9, 10, 11] } } }, { $project: { a: 1, b: 1, result: { $lte: ["$a", "$b"] } } } ]).pretty()
Resultado:
{ "_id" : 4, "a" : 250, "b" : "250", "result" : true }
{ "_id" : 5, "a" : "250", "b" : 250, "result" : false }
{ "_id" : 6, "a" : 250, "b" : NumberDecimal("250"), "result" : true }
{ "_id" : 7, "a" : NumberDecimal("250"), "b" : 250, "result" : true }
{ "_id" : 8, "a" : NumberDecimal("250"), "b" : NumberDecimal("250.00"), "result" : true }
{ "_id" : 9, "a" : NumberDecimal("250.00"), "b" : NumberDecimal("250"), "result" : true }
{ "_id" : 10, "a" : "2022-01-03T23:30:15.100Z", "b" : ISODate("2021-01-03T23:30:15.100Z"), "result" : true }
{ "_id" : 11, "a" : ISODate("2021-01-03T23:30:15.100Z"), "b" : "2021-01-03T23:30:15.100Z", "result" : false }
Valores nulos
null comparado com null retorna true.
{ "_id" : 12, "a" : 250, "b" : null }
{ "_id" : 13, "a" : null, "b" : 250 }
{ "_id" : 14, "a" : null, "b" : null }
Resultado:
{ "a" : 250, "b" : null, "result" : false }
{ "a" : null, "b" : 250, "result" : true }
{ "a" : null, "b" : null, "result" : true }
Campos ausentes
Se o segundo campo estiver ausente, retorna false. Se o primeiro estiver ausente, retorna true.
{ "_id" : 15, "a" : 250 }
{ "_id" : 16, "b" : 250 }
Resultado:
{ "a" : 250, "result" : false }
{ "b" : 250, "result" : true }
Infinito
{ "a" : Infinity, "b" : Infinity, "result" : true }
{ "a" : -Infinity, "b" : -Infinity, "result" : true }
{ "a" : Infinity, "b" : -Infinity, "result" : false }
{ "a" : -Infinity, "b" : Infinity, "result" : true }