mongodb元组比较(有序)
与这个问题类似: 我想用mongodb元组比较(有序),mongodb,mongodb-query,tuples,comparison,Mongodb,Mongodb Query,Tuples,Comparison,与这个问题类似: 我想用(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"] }})
(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);
请就您的意见和问题提供反馈。让我知道我能找到更好的解决方案