MongoDB: query to match each element in array with condition

Viewed 86

I have a doc collection (Events) something like,

[{
    _id: 1,
    followerRange: [
        {min: 5000, max: 50000, type: 'instagram'},
        {min: 1000, max: 5000, type: 'facebook'},
        {min: 1000, max: 25000, type: 'youtube'},               
    ]
},{
    _id: 2,
    followerRange: [
        {min: 10000, max: 50000, type: 'instagram'},
        {min: 5000, max: 10000, type: 'facebook'},
        {min: 10000, max: 100000, type: 'youtube'},               
    ]
},{
    _id: 3,
    followerRange: [
        {min: 10000, max: 500000, type: 'instagram'},
        {min: 10000, max: 100000, type: 'facebook'},
        {min: 50000, max: 100000, type: 'youtube'}, 
        {min: 50000, max: 100000, type: 'twitter'},              
    ]
}]

Which tells, whats the minimum followers/subscribers required on particular social channel to join the event.

Now, a user has three channels, something like,

[{
   type: 'instagram',
   followers: 7000
},{
   type: 'facebook',
   followers: 3000
},{
   type: 'youtube',
   followers: 12000
}]

Now the desired output from Event collection, to show to the this user, will be -

[{
    _id: 1,
    followerRange: [
        {min: 5000, max: 50000, type: 'instagram'},
        {min: 1000, max: 5000, type: 'facebook'},
        {min: 1000, max: 25000, type: 'youtube'},               
    ]
}]

Explanation:

  1. As user has all the channels which were required for event 1.
  2. Also user's followers count for respective channel fulfilled the criteria of min, max range.
  3. Basically, output from Event collection will be based on different users and their channels (and followers).

Please help me to figure out that how can I filter the events based on active user (channels). Thanks :)

2 Answers

I suggest you to change the structure of events collection like this:

{
    _id: 1,
    followerRange: {
        instagram: {min: 5000, max: 50000},
        facebook: {min: 1000, max: 5000},
        youtube: {min: 1000, max: 25000}          
    }
}

Then it's simple:

var instagramFollowers = 100;
db.events.find({"followerRange.instagram.min":{$lt: instagramFollowers}}, "followerRange.instagram.max":{$gt: instagramFollowers}}, ... etc.)

for now, you can try this query, I will post more efficient one later:

db.test.aggregate
      ([{$unwind:"$followerRange"},
{$match:{"$or":
[{"followerRange.min":{$lte:5001},"followerRange.max":{$gte:50000},"followerRange.type":"instagram"},
{"followerRange.min":{$lte:1000},"followerRange.max":{$gte:10000},"followerRange.type":"youtube"},
{"followerRange.min":{$lte:1000},"followerRange.max":{$gte:5000},"followerRange.type":"facebook"}]{$gte:40000},"followerRange.type":"instagram"}},
{$group:{_id:"$_id",ids:{$push:"$followerRange"},size:{$sum:1}}},
{$match:{size:3}}
])

Plz, ignore the formatting part.

Related