【问题标题】:Finding a document in an array using mongoldb driver for express使用 mongodb driver for express 在数组中查找文档
【发布时间】:2021-05-23 17:44:28
【问题描述】:

我有以下文件

   {
  "_id": ObjectId("6031dca77e510208f5d9cad5"),
  "userId": ObjectId("600b49554a19f1df7e7dee6e"),
  "resumes": [
    {
      "_id": "6031dca725f5b16515b3fde1",
      "pronouns": "They/Them",
      "name": "Jai",
      "contact": {
        "email": "jai.kirdatt@me.com",
        "phone": "2035690347"
      },
      "location": {
        "city": "Stamford",
        "state": "CT"
      },
      "resume_name": "test",
      "headline": "Full snack developer",
      "summary": "Passionate full snack developer",
      "links": {
        "dribble": "",
        "facebook": "",
        "github": "",
        "twitter": "",
        "website": ""
      },
      "experience": [],
      "talks": [],
      "licenses_and_certifications": [],
      "awards": [],
      "education": [],
      "side_projects": []
    },
    {
      "_id": ObjectId("6031de2e25f5b16515b3fde2"),
      "pronouns": "new",
      "name": "Jai",
      "contact": {
        "email": "jai.kirdatt@me.com",
        "phone": "2035690347"
      },
      "location": {
        "city": "Stamford",
        "state": "CT"
      },
      "resume_name": "new",
      "headline": "new",
      "summary": "new",
      "links": {
        "dribble": "",
        "facebook": "",
        "github": "",
        "twitter": "",
        "website": ""
      },
      "experience": [],
      "talks": [],
      "licenses_and_certifications": [],
      "awards": [],
      "education": [],
      "side_projects": []
    }
  ]
}

这是我从数组 resumes 中获取简历的代码

const client = dbClient();
const query = {
      'resumes._id': ObjectId(resumeId)
};

await client.connect();
const collection = client.db().collection(resumeCollection);
const result = await collection.findOne(query, { 'resumes.$': 1 });

上面还是返回了两份简历。另外,我不知道在哪里放置简历。$ 只返回一份文件。

我可以通过这个命令使用 mongo shell 获取正确的文档

db.resumes.find({"resumes._id" : ObjectId("6031dca725f5b16515b3fde1")}, {'resumes.$':1})

现在我不知道如何使用 Express 的 mongoldb 驱动程序获取正确的文档。

【问题讨论】:

    标签: node.js express mongodb-query


    【解决方案1】:

    Collection.find 方法接受 options 对象作为第二个参数,您必须在 projection 键中传递投影选项。

    db.resumes.find({ 'resumes._id': ObjectId('6031dca725f5b16515b3fde1') }, {
      projection: { 'resumes.$': 1 },
    })
    

    【讨论】:

    • 再次感谢您。我在想这不会是投影,因为我不想“投影”任何领域。它确实让我想知道为什么它是投影?我对 SQL 很了解,但似乎 SQL 技能转移在这里很难。
    猜你喜欢
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多