简体   繁体   中英

Mongoose / MongoDB query .find() any int > 0?

So I have a mongoose schema that looks like this.

var info = new mongoose.Schema(
{ '123': { available: { type: 'String' }, onOrder: { type: 'String' } },
  '456': { available: { type: 'String' }, onOrder: { type: 'String' } },
  '789': { available: { type: 'String' }, onOrder: { type: 'String' } }
});

I'm looking to find and number in the available field that is > 0. Only some of these will be filled at any given time. The "empty" String will always be filled with a number value of "0.00000000" if not some integer in it.

I'm looking for a query that will go through and find and string that isn't 0.00000000 or can convert the strings to integers then can find anything > 0.

I feel like my first thought of finding them based on strings is kinda hacky in a way and I'm looking for a more permanent way of retrieving numbers from a Database like this.

I've Attempted to accomplish this with $in already but I'm not able to get it to work.

you can do this in two ways, 1. $regexp 2. $where

  1. $regexp

check all the string contents are numbers [0-9], and start with non zero or zero or dot followed by 0-9

regexp would be /^[1-9][0-9]|[.0][1-9]/

  1. $where

use parseFloat check it's greater than zero

{ $where: function() { return parseFloat(this[123].available) > 0 } }

collection

  > db.info.find()
    { "_id" : ObjectId("5a5edabdfee4c182f509f3ea"), "123" : { "available" : "0.00000000", "onOrder" : { "type" : "xyz" } } }
    { "_id" : ObjectId("5a5edabdfee4c182f509f3eb"), "123" : { "available" : "0.00000010", "onOrder" : { "type" : "xyz" } } }
    { "_id" : ObjectId("5a5edabdfee4c182f509f3ec"), "123" : { "available" : "100000000", "onOrder" : { "type" : "xyz" } } }
    { "_id" : ObjectId("5a5edabdfee4c182f509f3ed"), "123" : { "available" : "abc", "onOrder" : { "type" : "xyz" } } }
    >

find with $regexp

> db.info.find( { "123.available" : /^[1-9][0-9]|[.0][1-9]/ } );
{ "_id" : ObjectId("5a5edabdfee4c182f509f3eb"), "123" : { "available" : "0.00000010", "onOrder" : { "type" : "xyz" } } }
{ "_id" : ObjectId("5a5edabdfee4c182f509f3ec"), "123" : { "available" : "100000000", "onOrder" : { "type" : "xyz" } } }
> 

find with $where

> db.info.find( { $where: function() { return parseFloat(this[123].available) > 0 } } );
{ "_id" : ObjectId("5a5edabdfee4c182f509f3eb"), "123" : { "available" : "0.00000010", "onOrder" : { "type" : "xyz" } } }
{ "_id" : ObjectId("5a5edabdfee4c182f509f3ec"), "123" : { "available" : "100000000", "onOrder" : { "type" : "xyz" } } }
> 
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM