1

I have this collection

 db.Tratte.insert(
    {
    "TransportID":["9901","9903"],
    "StopsBy":[
     {"Station":"Roma Termini",
     "StopsAt":ISODate("2016-01-01T09:05:00Z"),
     "LeavesAt":ISODate("2016-01-01T09:25:00Z")},
      {"Station":"Napoli Centrale",
     "StopsAt":ISODate("2016-01-01T10:37:00Z"),
     "LeavesAt":ISODate("2016-01-01T10:52:00Z")},
     {"Station":"Salerno",
     "StopsAt":ISODate("2016-01-01T11:35:00Z")}]
    })

and I want to extract the date (and only the date) when the train leaves "Roma Termini".

I tried the following query, but in this way I obtain all the information.

db.Tratte.find({"TransportID":"9901"},
   { StopsBy: 
     { 
        $elemMatch: { "Station": "Roma Termini" } 
     } 
    }

)

How can I extract only the "LeavesAt" field related to "Roma Termini"? Thanks

CiroRa
  • 492
  • 3
  • 13
  • you may find what you want here, probably http://stackoverflow.com/questions/25589113/how-to-select-a-single-field-in-mongodb – Elmer Dantas Dec 19 '16 at 11:17
  • I tried to use projection and adding {"LeavesAt":1} at the end of the query doesn't change anything and if I write my query without the elemMatch operator and try do {"LeavesAt":1} I obtain all the "LeavesAt" info, but I want only that related to my request ("Roma" in this case) – CiroRa Dec 19 '16 at 11:25
  • Try this - `db.Tratte.find({"TransportID":"9901"}, {StopsBy: { $elemMatch: { "Station": "Roma Termini" } }, "StopsBy.LeavesAt": 1 })` – Alex Dec 19 '16 at 11:26
  • It works. Oh my gosh, I forgot to prepend StopsBy!! Thank you. In this way I obtain "StopsBy": ["LeavesAt": ISODate()].... Is there a way to obtain directly only the value ISODate? – CiroRa Dec 19 '16 at 11:29
  • @Alex please write as answer and I'll approve it – CiroRa Dec 19 '16 at 12:00

2 Answers2

1

Use aggregate query -

db.Tratte.aggregate([
{$match: {"TransportID": "9901"}}, 
{$unwind: "$StopsBy"}, 
{$match: { "StopsBy.Station" : "Roma Termini" }}, 
{$project: {"StopsBy.LeavesAt": 1}} ])
rushUp
  • 4,391
  • 1
  • 8
  • 11
1

Try this

db.Tratte.find(
    {"TransportID":"9901"}, 
    {StopsBy: { $elemMatch: { "Station": "Roma Termini" } }, "StopsBy.LeavesAt": 1 }
) 

You need to use the dot notation to go 'inside' the StopsBy document

Alex
  • 37,502
  • 51
  • 204
  • 332