简体   繁体   中英

how to search an object inside an array of objects in mongoose?

i have my structure like this :

test{
  _id: 60eadb64b72caa2ae419e085,
  testid: 'hh',
  time: 45,
  testPassword: 123,
  startTime: 2021-07-11T11:52:04.245Z,
  Students: [
    {
      _id: 60eadb98b72caa2ae419e088,
      submission: '#*#org 0h #*##*#ret#*#',
      familyName: 'dsc',
      firstName: 'ccccc',
      group: 2,
      time: 0.8772833333333333
    },
    {
      _id: 60eadbb5b72caa2ae419e08c,
      submission: '#*#org 0h #*##*#ret#*#',
      familyName: 'eqf',
      firstName: 'aaaaa',
      group: 56,
      time: 1.357
    }
  ],
  __v: 0
}

i want to get just the object that has the _id: 60eadb98b72caa2ae419e088 from the array of students like this

    {
      _id: 60eadb98b72caa2ae419e088,
      submission: '#*#org 0h #*##*#ret#*#',
      familyName: 'dsc',
      firstName: 'ccccc',
      group: 2,
      time: 0.8772833333333333
    }

you can search inside array of objects in mongoose like this

db.collection.find({"Students._id": yourId})

you can go as deep as you want

db.collection.find({"Students.users.info.name": username})

and for a single match you can use findOne like this

db.collection.findOne({"Students._id": yourId})

the if you want only the object inside the Students array you can find it by javascript find function

const wantedObject = myObj.Students.find(e => e._id === "60eadb98b72caa2ae419e088")

You can use following aggregate to find you required result, I have tried at my local it is working fine

db.users.aggregate([
  {
    $match:{
      "Students._id":ObjectId("60eadb98b72caa2ae419e088")
    }
  },{
    $unwind:"$Students"
  },
  {
    $project: {
      submission:"$Students.submission",
      _id:"$Students._id",
      familyName:"$Students.familyName",
      firstName:"$Students.firstName",
      group:"$Students.group",
      time:"$Students.time", 
    }
  },
   {
    $match:{
      _id:ObjectId("60eadb98b72caa2ae419e088")
    }
  }
]);

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