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

时间:2021-07-11 12:54:04

标签: javascript node.js mongodb mongoose

我的结构是这样的:

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
    }

2 个答案:

答案 0 :(得分:0)

您可以像这样在猫鼬中搜索对象数组

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")

答案 1 :(得分:0)

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

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