简体   繁体   中英

How to match in double nested array fields using aggregate in mongodb?

Below is the code I am trying but unable to get the desired results. matching on jobid and email.

    mongoConn.aggregate({
                    collectionName: Collection.jobactivity,
                    data: [
                        { $unwind: '$jobs' },
                        { $match: { '$and': [{ 'jobs.jobid': candidateJobHistoryObj.jobid}, {'jobs.activity.email':  candidateJobHistoryObj.candidateemail  }] }},
                        { $project: ({ '_id': 0, 'jobs.activity.activityname': 1, 'jobs.activity.firstname': 1, 'jobs.activity.middlename': 1, 'jobs.activity.lastname': 1, 'jobs.activity.createddatetime': 1, 'jobs.activity.createdbyuserid': 1, 'jobs.activity.modifiedtime': 1, 'jobs.activity.modifiedbyuserid': 1 }) },
                        { $sort: { 'jobs.activity.createddatetime': -1 } }
                    ],
                })

Json code present in mongodb:

    {
        "_id" : ObjectId("61c9d42fc87b10aab2e6732a"),
        "accountid" : 122,
        "jobs" : [
            {
                "jobid" : 12,
                "activity" : [
                    {
                        "firstname" : "Vikas Yadav Bhai",
                        "middlename" : null,
                        "lastname" : "Yadav",
                        "email" : "candidate1@abc.com",
                        "activityname" : "inserted the data into candidate engagement workflow",
                        "modifiedbyuserid" : 151,
                        "modifiedtime" : ISODate("2015-12-01T05:30:00.000+05:30"),
                        "createdbyuserid" : 151,
                        "createddatetime" : ISODate("2015-08-12T00:00:00.000+05:30")
                    },
                    {
                        "firstname" : "Vikas Yadav Bhai",
                        "middlename" : null,
                        "lastname" : "Yadav",
                        "email" : "candidate2@abc.com",
                        "activityname" : "updated the job details",
                        "modifiedbyuserid" : 151,
                        "modifiedtime" : ISODate("2015-12-01T05:30:00.000+05:30"),
                        "createdbyuserid" : 151,
                        "createddatetime" : ISODate("2015-08-12T00:00:00.000+05:30")
                    }
    ]
    }
    ]
    }

I want to match the documents where email is => candidate1@abc.com and jobid = 12

db.collection.find({
  "jobs.activity.email": "candidate1@abc.com",
  "jobs.jobid": 12
})

Check out the official document on dot notation if you want more details.

Here is the Mongo playground for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM