Mitchell Ingram
Mitchell Ingram

Reputation: 706

How to search for multiple possible matches in an array

I have an array that contains arrays of json arrays. Sorted in a kind of page where One array = one page that contains an array of a table which contains json.

My model is:

var mongoose = require('mongoose');
    Schema = mongoose.Schema;
var Links = new Schema({
        country: {country:String,league:Array},
        team:String,
        dayMoney:[{day:String, money:String}]

    });
mongoose.model('team', Links)

And my code is:

Team.find({dayMoney: {"$in": [{money: '0.7800000000000002'}, { day: '24 May 2015', money: '72.61000000000001' } ]}},function(err, results) { etcc..

Problem is it keeps returning with nothing. I know my model is probably the issue here.

dayMoney: [ { money: '0', day: '16 Aug 2014' }, { money: '-1', day: '17 Aug 2014' }, { money: '-1', day: '18 Aug 2014' }, { money: '1.27', day: '23 Aug 2014' }, { money: '1.27', day: '24 Aug 2014' }, { money: '1.27', day: '25 Aug 2014' }, { money: '3.91', day: '30 Aug 2014' }, { money: '3.91', day: '31 Aug 2014' }] 

Is an example of console.loging one of the objects

Upvotes: 1

Views: 65

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

Use $elemMatch with an $or condition to specify the specfic elements of the array to match. The $in operator is for an argument of arrays as single values, not just for querying arrays:

Team.find({
    "dayMoney": {
        "$elemMatch":  {
           "$or": [ 
              { "money": '3.91'}, 
              { "day": '16 Aug 2015', "money": '0' }
           ]
        }
    }
},function(err,results) {
    // something useful here
})

I'm also subtituting your values there for things that actually match your sample data given.

Be careful because these are "strings" ( probably not a great idea ) and you seem to also have floating point rounding issues in how you are determining the values. A String or any value must be an "exact match" with the exception of Numeric or Date values that could fall within a range. Or of course a regular expression for strings.

Upvotes: 2

Related Questions