Dev kumar
Dev kumar

Reputation: 7

Mongodb: query using value from a nested array

I have the following schema, blog collection & friendscoll as below

blogpostcollection
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5826"),
      "author" : "joe",
      "text" : "Here is the text...",
      "userid" : 0
    }
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5827"),
      "author" : "blake",
      "text" : "Here is the text...",
      "userid" : 1
    }
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5828"),
      "author" : "joe",
      "text" : "Here is the text...",
      "userid" : 2
    }

myfriendscoll
    {
      "myid": 999,
      "data": [
        {
          "uid": 1, 
          "name": "Raul"
        }, 
        {
          "uid": 3, 
          "name": "John K"
        } ]
    }

I want to find all documents in blogpostcollection, where the userid exists as uid, in the myfriendscoll collection. So in effect, something like..

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
db.blogpostcollection.find( {"userid" : {$in : user.data.uid}});

This doesn't work, but is there a way to get it to work?...Thanks!

Upvotes: 0

Views: 185

Answers (2)

Asya Kamsky
Asya Kamsky

Reputation: 42342

If you are using development version 2.1 or when you move to 2.2 once it's released you can use the aggregation framework to get the format you want back from the first query:

var ret=db.myfriendscoll.aggregate([
             {$match:{"myid" : 999}},
             {$project:{_id:0,uid:"$data.uid"}}
]);
var uids=ret.result[0].uid;
db.blogpostcollection.find({userid:{$in:uids}})

Upvotes: 1

narced133
narced133

Reputation: 752

You'll need to extract the actual uid values into an array to use with $in. Try this:

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
var uids = user.data.map(function(v){ return v.uid });
db.blogpostcollection.find( {"userid" : {$in : uids}});

Upvotes: 0

Related Questions