4

how can I select email by Id from user collection like this:

select emailAddress from users where _id="***"

I select it like this in mongo but result is not true

db.getCollection('users').find({_id: "QYoHQkTuTXnEC6Pws"},{ "emails.0.address": 1})

Updated: Sample file

{
  "_id": "QYoHQkTuTXnEC6Pws",
  "createdAt": ISODate("2017-03-09T06:21:29.664Z"),

  "emails": [{
    "address": "x@gmail.com",
    "verified": true
  }],
  "isDeleted": false
}
sidgate
  • 14,650
  • 11
  • 68
  • 119
Mehrnoosh
  • 879
  • 2
  • 12
  • 27

2 Answers2

4

Looking at your query, you are expecting to find only first email and only the address field for the given ID. Depending on the expected output, you can try following queries and choose.


Will give you all addresses

db.users.find({_id:'QYoHQkTuTXnEC6Pws'}, { "emails.address": 1})

Response

{
    "_id" : "QYoHQkTuTXnEC6Pws",
    "emails" : [ 
        {
            "address" : "x@gmail.com"
        }, 
        {
            "address" : "x2@gmail.com"
        }
    ]
}

Will give you only first email address from the array. You have explicitly remove all other fields

db.users.find({_id:'QYoHQkTuTXnEC6Pws'}, 
   { 'emails.verified':0,  _id:0, createdAt: 0, isDeleted: 0, "emails": {$slice: 1}})

Response

{
    "emails" : [ 
        {
            "address" : "x@gmail.com"
        }
    ]
}

Alternatively you can use aggregation to get expected result

db.users.aggregate({$match: {_id:'QYoHQkTuTXnEC6Pws'}}, 
   {$project: {_id:0,email: {$arrayElemAt: ['$emails.address',0]}}})

Response {"email" : "x@gmail.com"}

sidgate
  • 14,650
  • 11
  • 68
  • 119
1

I got the answer for your requirement;

db.inventory.aggregate([{
  $match: {
    _id: "QYoHQkTuTXnEC6Pws"
  }
}, {
  $unwind: "$emails"
}, {
  $replaceRoot: {
    newRoot: "$emails"
  }
}, {
  $project: {
    address: 1
  }
}])

This would first match the correct document, then $unwinds the emails field to expose objects inside, then move the root to it to get focus close to address field, then $project to only get address, which results with your example data (had it contained multiple emails);

{ "address": "x@gmail.com" }
{ "address": "xy@gmail.com" }
buræquete
  • 14,226
  • 4
  • 44
  • 89