就类似于这个问题:mongodb query multiple pairs using $in
我想用 (first, last) >= ('John', 'Smith')
找到前 10 个全名。使用 MySQL 很简单:
SELECT first, last
FROM names
WHERE (first, last) >= ('John', 'Smith')
ORDER BY first, last
LIMIT 10
在 MongoDB 中可能是这样的:
db.Names.find({ "[first, last]": { $gte: [ "John", "Smith"] }})
.sort({first: 1, last: 1})
.limit(10)
但我不知道如何编写正确且简单的查询。
这可能可行但过于冗长:
db.Names.find({ $or: [
{ first: "John", last: { $gte: "Smith" }},
{ first: { $gt: "John" }}
]}).sort(...)
最佳答案
对于这个mysql查询,你可以使用下面的mongoDB查询
SELECT first, last
FROM names
WHERE (first, last) >= ('John', 'Smith')
ORDER BY first, last
LIMIT 10
Mongodb查询
db.Names.find(
{ $expr: {
$or: [
{ $gte: [{ $strLenCP: "$first" }, { $strLenCP: "John" }] },
{ $gte: [{ $strLenCP: "$last" }, { $strLenCP: "Smith" }] }
]
}},
// project from mongodb result same as select in mysql
{ first: 1, _id: 0, last: 1 })
// sort in mongodb
.sort({ first: 1, last: 1 })
// with limit 10
.limit(10);
关于mongodb 元组比较(有序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204544/