Skip to content

Instantly share code, notes, and snippets.

@sirusdas
Created September 3, 2018 11:58
Show Gist options
  • Save sirusdas/716ffccdaf3fe16f87692c58da5dd690 to your computer and use it in GitHub Desktop.
Save sirusdas/716ffccdaf3fe16f87692c58da5dd690 to your computer and use it in GitHub Desktop.
Mongo Db queries

Suppose you have a structure like

a: {
  b: [
    {
      c: 1,
      d: 2
    },
    {
      c: 3,
      d: 4
    }
  ]
}

Now search for d=4 and display only the c value i.e 3 in this case. The code is

db.users.aggregate([ 
{$match : { _id:ObjectId("5b8a7174e7f55107e694d323"), 
    "b.d": {$in : ['4']} } }, 
{$unwind : "$b" }, 
{$match : { "b.d" : "4" }}, 
{$project : { d : "$b.d", c: "$b.c",

    _id:0
}} ]);

Some other quries

db.users.aggregate([
    // Get just the docs that contain a shapes element where color is 'red'
    {$match: {
        _id: ObjectId("5b8a7174e7f55107e694d323"),
        
        "referral_details.email": {$in : ['[email protected]']}
    }},
    {$project: {
        referral_details: {$filter: {
            input: '$referral_details',
            as: 'referral_details',
            cond: {$eq: ['$$referral_details.email', '[email protected]']}
        }},
        _id: 0
    }}
]);

AND

db.users.find({
    _id:ObjectId("5b8a7174e7f55107e694d323"), 
    "referral_details.email": {$in : ['[email protected]']}
    
},{"referral_details.referral_id.$":1});

@devesh-dd
Copy link

hello bhaiya . Can U please tell me how to download amazons/coursekart videos. Please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment