如何在mongoose中的对象数组中搜索对象?

ix0qys7i  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(337)

我的结构如下:

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
}

我只想从像这样的学生数组中获取id为60eadb98b72caa2ae419e088的对象

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

tjjdgumg1#

您可以像这样在mongoose中搜索对象数组内部

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

你想走多远就走多远

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

对于单个匹配,您可以使用 findOne 这样地

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

如果只想在students数组中找到对象,可以通过javascript找到它 find 功能

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

8nuwlpux2#

您可以使用以下聚合来找到您所需的结果,我已经在我的本地尝试过了,它工作正常

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")
    }
  }
]);

相关问题