mongodb tuple comparison (ordered)

Viewed 150

Just similar to this question: mongodb query multiple pairs using $in

I want to find first 10 full names with (first, last) >= ('John', 'Smith'). It is simple with MySQL:

SELECT first, last 
FROM names
WHERE (first, last) >= ('John', 'Smith') 
ORDER BY first, last 
LIMIT 10

In MongoDB maybe something like:

db.Names.find({ "[first, last]": { $gte: [ "John", "Smith"] }})
   .sort({first: 1, last: 1})
   .limit(10)

But I do not know how to write the correct and simple query.

This may be work but too verbose:

db.Names.find({ $or: [
           { first: "John", last: { $gte: "Smith" }},
           { first: { $gt: "John" }}
    ]}).sort(...)
1 Answers

You can use below mongoDB query in respect of this mysql query

SELECT first, last 
FROM names
WHERE (first, last) >= ('John', 'Smith') 
ORDER BY first, last 
LIMIT 10

Mongodb query

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