MongoDB 3.6.3新手求助:如何按值搜索嵌套JSON任意键
Hey there! Since you're a MongoDB newbie on version 3.6.3 and need to find documents where any key inside that big JSON field matches your target value (without knowing all the key names), here are a couple of practical approaches to try out:
MongoDB 3.6 supports $objectToArray, which lets you convert your nested JSON object into an array of {k: "keyName", v: "value"} pairs. You can then filter this array to check if any value matches your regex.
Here's the query you can run for your booking collection, assuming the large JSON is stored in the result field:
db.getCollection('booking').find({ $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: "$result" }, cond: { $regexMatch: { input: "$$this.v", regex: /.*small dogs.*/ } } } } }, 0 ] } })
Let me break this down:
$objectToArray: "$result"turns your JSON object into an array of key-value pairs.$filterkeeps only the pairs where the value ($$this.v) matches your regex.$sizecounts how many matching pairs exist, and$gt: [size, 0]ensures there's at least one match.
Pro tip: If you're looking for an exact value instead of a regex, replace the $regexMatch condition with { $eq: ["$$this.v", "small dogs"] } for better performance.
If you're working with a small dataset and don't mind a full collection scan, you can use a JavaScript function to loop through all keys in the result object and check for matches:
db.getCollection('booking').find(function() { for (const key in this.result) { // Skip if the value is null/undefined to avoid errors if (this.result[key] && /.*small dogs.*/.test(this.result[key])) { return true; } } return false; })
Just keep in mind: MongoDB can't use indexes with JavaScript-based queries, so this will be slow on large collections. Use this only as a quick fix for small datasets.
- Regex Tweak: Your original regex
/.*small dogs*/has a trailing*that means "zero or more 's' characters". If you want to match any string containing "small dogs", use/.*small dogs.*/(the final.*matches any characters after) or just/small dogs/(since regex is partial by default). - Nested Keys: If your JSON has nested objects (not just top-level keys), the first approach won't catch those. MongoDB 3.6 doesn't support recursive aggregation natively, so you'd either need to flatten your schema or upgrade to a newer MongoDB version (like 4.4+) for more advanced aggregation tools.
内容的提问来源于stack exchange,提问作者Raj

