mongodb 元组比较(有序)

标签 mongodb mongodb-query tuples comparison

就类似于这个问题: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/

相关文章:

java - MongoDB java驱动程序: can't find jar that contains org. bson.types.ObjectId

javascript - 如何返回 mongoDB 中具有连字符字段的映射函数

php - 寻找适合我们案例的 NoSQL 数据库

node.js - 如何一次查询所有模型 Mongoose?

javascript - 如何从命令行更新 mongodb 字符串字段?

generics - 是否可以为 F# 元组创建扩展方法

python - 如何在元组中复制元素 n 次

node.js - 为数组中的每个元素添加唯一值

Python 元组而不是列表

php - 如何从对象中获取 "any"mongodb 结果键