Mongodb string comparison with slash

Why do i get empty result then compare strings with slash?

db.x.find( { path: { $gt: "/1"} } ).sort({ path:1 })

// x collection field path type string:
/1607721617028
/1607721618266
/1607721619028

I don’t think $gt works that way. You might want to use $regex instead or do an aggregation that strips the leading slash and then do a numeric comparison.

  1. i have difference values. all string and cant split or cast to number
    /1607720653313
    /1607720653313/1607721600895
    /1607720653313/xxxx/1607721600895
  2. i watch manual , they do it with $gt
    https://technotip.com/4101/string-comparison-mongodb/
    image

When I use your sample data and your query I have the expected result.

> db.test.insertOne( { path : "/1607721617028" } )
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5fd41c6a3be099655d525122")
}
> db.test.insertOne( { path : "/1607721618266" } )
{
	"acknowledged" : true,
	"insertedId" : ObjectId("5fd41c913be099655d525123")
}
> db.test.find( { path: { $gt: "/1"} } )
{ "_id" : ObjectId("5fd41c6a3be099655d525122"), "path" : "/1607721617028" }
{ "_id" : ObjectId("5fd41c913be099655d525123"), "path" : "/1607721618266" }

There is not reason why I have output and you don’t. I suspect that there is something you are not sharing that point us to the wrong direction.

1 Like