0

A document contains an array of object each object contains a key i want to find all the object that matches the key in mongoose. Below is the sample schema:

const TalentSchema = new mongoose.Schema({
name: String,
  dev_task: [
        {
          development_training: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'TrainingModule',
          },
          developlink: String,
        },
      ],  
})

I want to match the document that have development_training to given Id. How can i do that ?

Update : Sample Data

[
  {
    "name": "name1",
    "dev_task": [
      {
        "development_training": 1,
        "developlink": ""
      },
      {
        "development_training": 2,
        "developlink": ""
      }
    ]
  },
  {
    "name": "name2",
    "dev_task": [
      {
        "development_training": 1,
        "developlink": ""
      }
    ]
  },
]

It should return This : -

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "dev_task": [
      {
        "developlink": "",
        "development_training": 1
      }
    ],
    "name": "name1"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "dev_task": [
      {
        "developlink": "",
        "development_training": 1
      }
    ],
    "name": "name2"
  }
]
Shashank Dubey
  • 353
  • 1
  • 6
  • 17

1 Answers1

1

As explained into docs, mongo uses dot notation.

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

And this is exactly we want.

So to access your document you need to do dev_task.development_training into find query in this way:

db.collection.find({
  "dev_task.development_training": 1
})

Example here

Note that using mongoose is the same query:

yourModel.findOne({"dev_task.development_training": yourId}).then(result => {/*...*/})
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Hey J.F i have a doubt. This query returns all the object that have at least one object with "dev_task.development_training": 1 also it returns the array that have two object with different dev.task.development_training. Please check my question i just updated! – Shashank Dubey Feb 04 '21 at 10:35