0

For example on my object below. What if i dont want to return the whole object I just want to return DateInStock . How do we query that in mongo using node js ?

Object

{
    "message": "success",
    "data": [
        {
            "_id": "5ddc97ebeefab43ae69c09a3",
            "VIN": "1D3HB18T29S817612",
            "Body": "Quad Cab Pickup",
            "BookValue": "6686",
            "DateInStock": "08/01/2019",
            "Description": "",
            "Doors": 4,
            "DriveType": "RWD",
            "EngineCylinders": "8",
            "EngineDisplacement": "5.7L",
            "ExteriorColor": "Deep Water Blue Pearl",...
Community
  • 1
  • 1

1 Answers1

1

You can pass an object with the fields you want to include or exclude as a second parameter.

value of 1 will include the field and 0 will exclude it.

note that _id returns by default so you have to pass _id: 0 if you want to exclude it

db.yourColletion.find({ _id: "5ddc97ebeefab43ae69c09a3" }, { "DateInStock": 1 })
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • but what if i have to exclude 10 fields ? do i need to do it one by one by setting each field to 0 ? –  Nov 26 '19 at 03:30
  • @JhonCull It will return only the fields with the value of 1, if you pass only properties with the value of 0 all of the remaining fields will return. So only use all fields of 0 or 1 – Asaf Aviv Nov 26 '19 at 03:32
  • @JhonCull Also the only exception is the `_id` property that you can pass 0 or 1 with the fields you want but other then the _id keep all fields with the value of 1 or 0 – Asaf Aviv Nov 26 '19 at 03:35
  • does it direcly work this way { "DateInStock": 1 }? or i need to use projection –  Nov 26 '19 at 03:36
  • @JhonCull No need to project, use it the same as the code in my answer – Asaf Aviv Nov 26 '19 at 03:38
  • does not work i did try , i am receiving error callback.apply is not a function TypeError: callback.apply is not a function myquery Vehicle.model.find(query ,{}, {'VIN' : 1 } , pagination ).exec(function (err, vehicle) { –  Nov 26 '19 at 03:39
  • @JhonCull You pass it as the third parameter instead of the second `Vehicle.model.find(query , {'VIN' : 1 },pagination).exec(function (err, vehicle) {})` – Asaf Aviv Nov 26 '19 at 03:41
  • @JhonCull any time! – Asaf Aviv Nov 26 '19 at 03:53