0

I currently have an array of multiple id's which reference subdocuments. What I need to do is search collections for these Id's and return the information associated with them.

var ids =['58c2871414cd3d209abf4fc0','58c2871414cd3d209abf5fc0'];
User.aggregate(
      {$unwind : "$position"},
      {$match:{'_id': { $in: [

     // need to reference the ids array here

    ]}
}
}, function(err, docs){
     console.log(docs);
});

});

My user schema is as follows:

var User = new Schema({
id: String,
name: String,
position: [{
          _id:String,
          title: String,
          location: String,
          start: String,
          term:Number,
          description:String,
          date: {type: Date, default: Date.now},

So basically what I need to do is return the entire Position subdocument if it matches an id from the array. Any Ideas?

user
  • 395
  • 2
  • 11
  • 28
  • What is your mongo server version ? Are you searching position inside a single user document ? – s7vr Apr 16 '17 at 17:27
  • @Veeram my mongo version is v3.2.10. What I have is multiple users(user schema) and within these users there are various position subdocuments (all of which have individual id's associated with them) what I need to do is search all of the users , unwind the position subdocuments and return the ones which match the id's in the array of id's I have – user Apr 16 '17 at 17:42
  • Try `User.aggregate( { $unwind : "$position" }, { $match: { "position._id": { $in: ids } } }, { $project: { "position": 1 } } )` – s7vr Apr 16 '17 at 17:45
  • @Veeram Im unfortunately getting a blank array back from that code :( – user Apr 16 '17 at 17:51
  • Looks like aggregate doesn't do casting ids from string to objectIds. Try casting the `_ids` to `var ids =[mongoose.Types.ObjectId('58c2871414cd3d209abf4fc0'), mongoose.Types.ObjectId('58c2871414cd3d209abf5fc0')];` before sending it to `$match` – s7vr Apr 16 '17 at 17:54
  • Thanks @Veeram thats works now! :) thanks for the help – user Apr 16 '17 at 18:01
  • Actually, @Veeram would you know how to order the results by the order of the array? Right now it seems to be in the order of how they are found in the database, for example the second ID in the array is actually before the first one in the database, so that seems to be coming back first... – user Apr 16 '17 at 18:10
  • Np. This is not possible for 3.2 version as far as I know. You will have to sort them by some field explicitly for definite order before projecting. Other option will be go through them and sort on client side after getting results. https://jira.mongodb.org/browse/SERVER-7528 – s7vr Apr 16 '17 at 18:12

0 Answers0