MongoDB元组比较(有序)

3

与此类似的问题: mongodb使用$in查询多个键值对

我想要查找前10个满足(first, last) >= ('John', 'Smith')条件的全名。在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(...)

请就您的这个问题和那个问题提供反馈。请告诉我是否可以找到更好的解决方案。 - Ashok
1个回答

0

您可以使用以下的mongoDB查询来对应这个mysql查询

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接