You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mongoose查询parent数组含指定ID的MongoDB文档

Query All Descendants of "child" (_id: 2) in Mongoose

Got it, let's break down how to fetch all descendants of the document with _id: 2 (your "child" entry) using Mongoose.

Looking at your data structure, each document's parent array stores the full lineage of its ancestors. So any descendant of the "child" will have 2 somewhere in its parent array. That makes the query straightforward:

Mongoose Query Code

Assuming your model is named something like Node (adjust to match your actual model name):

const Node = require('./models/node'); // Import your Mongoose model

async function fetchChildDescendants() {
  // Find all documents where the parent array contains 2
  const descendants = await Node.find({ parent: 2 });
  
  console.log('All descendants of "child" (_id:2):', descendants);
  // This will return _id:3 (grandchild), _id:4, _id:5 (greatgrandchildren)
}

// Call the function
fetchChildDescendants();

Why This Works

In MongoDB, when you query an array field with a single value (like parent: 2), it automatically matches all documents where that value exists anywhere in the array. Perfect for your use case, since all descendants of the "child" will include 2 in their ancestor lineage.

Bonus: If You Need Only Direct Children

If you ever want to fetch only direct children of "child" (just _id:3 in your sample data), you can narrow the query to match documents where 2 is the last entry in the parent array (since your lineage is ordered from root to immediate parent). Here's how:

const directChildren = await Node.find({
  parent: {
    $size: 2, // The parent array has exactly 2 elements (root + immediate parent)
    $elemMatch: { $eq: 2 } // And 2 is one of those elements
  }
});

Or using array index syntax (since the immediate parent is the last element, index 1 for an array of length 2):

const directChildren = await Node.find({ 'parent.1': 2 });

内容的提问来源于stack exchange,提问作者Leo Alfando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:09:53