技术求助:提取JSON中olderAdress字段生成新记录并保留原记录
Solution for Expanding JSON User Records with Older Addresses
Got it, let's work through this problem together. You need to keep your original user record, plus create new duplicate records for each entry in the olderAdress array—each new record swaps in the localization and createDate from the address entry while retaining all other user details. Here are two practical solutions depending on your use case:
Option 1: MongoDB Aggregation Pipeline (Best for Database Processing)
Since your desired output includes ObjectId, I’m assuming you’re working with MongoDB. This pipeline will directly transform your documents in the database:
db.yourCollectionName.aggregate([ // Step 1: Save original user data (without olderAdress) and isolate address entries { $addFields: { originalUser: { $mergeObjects: ["$user", { olderAdress: "$$REMOVE" }] }, addressEntries: "$user.olderAdress" } }, // Step 2: Generate user records for each address entry { $addFields: { addressUsers: { $map: { input: "$addressEntries", as: "addr", in: { $mergeObjects: [ "$originalUser", { localization: "$$addr.localization", createDate: "$$addr.createDate" } ] } } }, // Wrap original user in array to prepare for concatenation originalRecord: ["$originalUser"] } }, // Step 3: Combine original record and address-based records { $addFields: { allRecords: { $concatArrays: ["$originalRecord", "$addressUsers"] } } }, // Step 4: Expand the combined array into individual documents { $unwind: "$allRecords" }, // Step 5: Format each document with ObjectId and user details { $replaceRoot: { newRoot: { _id: { $function: { body: "() => new ObjectId()", args: [], lang: "js" } }, user: "$allRecords" } } } ])
Quick Breakdown:
$mergeObjectsoverwrites thelocalizationandcreateDatefields while preserving all other user data.- The
$functionfor generatingObjectIdrequires MongoDB 4.4+. If you’re on an older version, generate IDs client-side or use$uuidas an alternative. - Replace
yourCollectionNamewith your actual MongoDB collection name.
Option 2: Pure JavaScript (For Client-Side/Node.js Processing)
If you’re working with JSON data directly in code, this approach transforms the data locally:
// Import ObjectId if using Node.js with MongoDB driver // const { ObjectId } = require('mongodb'); const originalData = [ { "user": { "type": "PF", "code": 12345, "Name": "Darth Vader", "currency": "BRL", "status": "SINGLE", "localization": "NABOO", "createDate": 1627990848665, "olderAdress": [ { "localization": "DEATH STAR", "createDate": 1627990848775 }, { "localization": "TATOOINE", "createDate": 1627990555888 } ] } } ]; // Extract original user data (remove olderAdress field) const originalUser = { ...originalData[0].user }; delete originalUser.olderAdress; // Initialize result with the original user record const result = [ { _id: `ObjectId("${new ObjectId().toString()}")`, user: originalUser } ]; // Add new records for each older address originalData[0].user.olderAdress.forEach(addr => { result.push({ _id: `ObjectId("${new ObjectId().toString()}")`, user: { ...originalUser, localization: addr.localization, createDate: addr.createDate } }); }); // Output the final result console.log(JSON.stringify(result, null, 2));
Quick Breakdown:
- The spread operator (
...) copies all original user properties, and we only overwrite the necessary fields from each address entry. - If you don’t need the
ObjectId("...")string format, usenew ObjectId()directly to get the raw hex string.
内容的提问来源于stack exchange,提问作者Patrick Teixeira
相关产品推荐
相关产品推荐

