MongoDB Query How to get one field value?

Hi guys i am new to mongodb i am trying to write a query to get a single field value from db:

{
    "_id" : "vK4PvdNBfBbdv92PH",
    "ownerId" : "J8MpsWChPQdET6jwQ",
    "createdAt" : ISODate("2018-07-04T07:25:28.406Z"),
    "spots" : [ 
        {
            "name" : "spot1",
            "construction" : false,
            "constructingBuildingName" : "",
            "buildingName" : "factory",
            "level" : 1,
            "startTime" : 0,
            "finishTime" : 0
        }, 
        {
            "name" : "spot2",
            "construction" : true,
            "constructingBuildingName" : "Farm",
            "buildingName" : "",
            "level" : 0,
            "startTime" : 1530863511,
            "finishTime" : 1530864011
        }, 
        {
            "name" : "spot3",
            "construction" : false,
            "constructingBuildingName" : "",
            "buildingName" : "",
            "level" : 0,
            "startTime" : 0,
            "finishTime" : 0
        }
    ]
}

In this case I am trying to get under spot2 “constructingBuildingName” s “Farm” value.

What i wrote is :
var constructingBuildingName = Towns.find({ownerId:userid,spots:{$elemMatch:{name:spot}}});
spot is = “spot2”

What should be the rest ?

Hi,
If I understand correctly, you want to get only ‘spots.constructingBuildingName’ value ? You can do that using Field specifiers (check the doc).

Like this:

Towns.find(
  { 
    ownerId:userid, 
    'spots.name': spot,
  },
  {
    fields : {
      'spots.constructingBuildingName': 1,
    }
  }
);

@atf, that will return

{
    "_id" : "vK4PvdNBfBbdv92PH",
    "spots" : [ 
        {
            "constructingBuildingName" : ""
        }, 
        {
            "constructingBuildingName" : "Farm"
        }, 
        {
            "constructingBuildingName" : ""
        }
    ]
}

because the field specifier can only pick fields maintaining the paths. It can’t change the shape or filter array fields.

@lastpeony, you’ll have to use aggregation for that.
Try this:

const { constructingBuildingName } = _.first(
    Towns.aggregate([
        { $match: { ownerId: userid, 'spots.name': spot } },
        { $limit: 1 },
        { $unwind: '$spots.name' },
        { $match: { 'spots.name': spot } },
        { $limit: 1 },
        { $project: { constructingBuildingName: '$spots.constructingBuildingName', _id: 0 } },
    ])
) || {};