提问人:auntyellow 提问时间:10/2/2019 最后编辑:Ashokauntyellow 更新时间:10/3/2019 访问量:274
MongoDB 元组比较(有序)
mongodb tuple comparison (ordered)
问:
与这个问题类似:mongodb 使用 $in 查询多个对
我想找到前 10 个全名。MySQL很简单:(first, last) >= ('John', 'Smith')
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(...)
答:
0赞
Ashok
10/3/2019
#1
您可以针对此 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);
评论