gpt4 book ai didi

mongodb 元组比较(有序)

转载 作者:行者123 更新时间:2023-12-05 07:18:41 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com