简体   繁体   中英

How to get only part of document in MongoDB with Node.js?

"Geography": {
  "Tourism": {
    "B001": {
      "code": "B001",
      "max": " 140",
      "min": " 97",
      "minWithQuota": " 91"
    }
  }
},
"MathAndPhysic": {
  "IT": {
    "B183": {
      "code": "B183",
      "max": "140",
      "min": " 50",
      "minWithQuota": "none",
      "quotes": []
    }
  }
}

I have some collection and I would like to get only the "B001" object. I tried getting it through

db.subjects.findOne (
{"Geography.Tourism.B001": {$exists: true}},
{_id: 1," Geography.Tourism.B001": 1})

but the result was the entire document. how do I get this result?

"B001": {
      "code": "B001",
      "max": " 140",
      "min": " 97",
      "minWithQuota": " 91"
    }

PS Interestingly if you try to use the same command in MongoShell you will get the desired result

try projecting field using reference $ ,

db.subjects.findOne(
  { "Geography.Tourism.B001": { $exists: true } },
  { "B001": "$Geography.Tourism.B001" }
);

Playground

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