簡體   English   中英

如何在貓鼬的對象數組中搜索對象?

[英]how to search an object inside an array of objects in 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
    }

您可以像這樣在貓鼬中搜索對象數組

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

你可以隨心所欲

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

對於單個匹配項,您可以像這樣使用findOne

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

如果你只想要學生數組中的對象,你可以通過 javascript find函數找到它

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

您可以使用以下聚合來查找所需的結果,我在本地嘗試過它工作正常

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM