0

this is the find({}) query,

[ { state: 
 [ [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   [Object],
   ... 4020 more items ] } ]

this is my schema,

var state_schema= mongoose.Schema({
state:[
    {
        id: String,
        name: String,
        country_id: String
    }
]

});

this is the object;

{
                    "id" : "2624",
                    "name" : "Boaco",
                    "country_id" : "158",
                    "_id" : ObjectId("59f95fb9180e291fcc90683b")
            },

i need to get all objects wich have the country_id "158". i cant get it, this is what i tried..

1. state.find({state:{"$in":[{country_id:req.body.country_code}]}},{_id:0, __v:0}

this results an empty array.

2.  state.find({state: {$elemMatch: {country_id: req.body.country_code}}},{_id:0,__v:0}

here i am getting all the results, which means filtering is not working (results simple find({})).

3.  state.find({'state.rooms': {country_id: req.body.username}}, function (err,state)

here also [] empty array returns.

how to do this?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Your `2` was closest. But this just "selects the document", and it does not "filter the array". Getting singular or multiple matches from an array is a different process, which is covered in the [linked question and answers](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection). As a side note, you actually appear to be doing things wrong and have everything stored in an array of a single document, where they should actually all be separate documents in a collection by themselves. That's what it looks like, anyway. – Neil Lunn Nov 01 '17 at 11:06
  • state.find({"state.country_id":"2"},{state:{$elemMatch: {country_id: "158"}}} here i got only one result, i want to get all the objects which have country_id:158 but why –  Nov 01 '17 at 11:22
  • Keep reading the answers until you see one with `$filter`. Like I said though, you're doing this all wrong. These should be documents in their own collection. You put documents into an array of a single document, when you should have stored them as separate documents themselves. – Neil Lunn Nov 01 '17 at 11:25
  • i know bro, the reason why i am still using it because i inserted a 4mb of document using mongoose. thats really slow process. so thats why. by the way i need to use aggregate instead of find. correct? –  Nov 01 '17 at 11:34
  • That's what the answers say. – Neil Lunn Nov 01 '17 at 11:39
  • Thank you! by the way i droped my database! –  Nov 01 '17 at 11:43

0 Answers0