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

如何在MongoDB的对象中查找指定键对应的数组元素?

How to Get the Array for Key "1162" in MongoDB's "timestamps" Object

Got it, let's walk through how to retrieve the array associated with the key "1162" inside the "timestamps" object in your MongoDB document. First, let's recap your document structure for clarity:

{
  "timestamps": {
    "1200": ["390.288", "390.818", "So"],
    "1175": ["381.778", "382.248", "so"],
    "1183": ["383.668", "383.928", "a"],
    "1144": ["372.588", "372.718", "up"],
    "1162": ["377.638", "377.928", "rial"],
    "1218": ["395.798", "395.868", "me"],
    "1145": ["372.718", "373.188", "So"]
  }
}

Method 1: Use Projection with find()

If you want to fetch the specific field directly from the database (without retrieving the entire document), use projection in the find() method. Replace yourCollectionName with the actual name of your collection:

db.yourCollectionName.find(
  {}, // Leave empty to match all documents; add a filter here if targeting a specific doc
  { "timestamps.1162": 1, _id: 0 } // 1 = include this field, _id:0 excludes the default _id
)

This will return a result like:

{ "timestamps": { "1162": ["377.638", "377.928", "rial"] } }

Method 2: Extract the Array Directly in the Shell

If you're working in the MongoDB shell and want to get just the array value (without the surrounding object keys), fetch the document first then access the field using bracket notation (since the key is a string of numbers):

// Fetch the document (add a filter inside findOne() if needed)
const doc = db.yourCollectionName.findOne({});

// Extract the target array
const targetArray = doc.timestamps["1162"];

// Print the result
printjson(targetArray);

This will output just the array:

["377.638", "377.928", "rial"]

Method 3: Aggregation for Batch Processing

If you need to process multiple documents and extract this array for each, use the aggregation framework's $project stage:

db.yourCollectionName.aggregate([
  { $match: {} }, // Add filters here to target specific documents
  { $project: {
      _id: 0, // Exclude _id if not needed
      "1162_array": "$timestamps.1162"
    }
  }
])

This will return a list of objects, each containing the 1162_array field with the corresponding array value.

内容的提问来源于stack exchange,提问作者Kiran Suvarna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:13:38