我正在尝试使用MongoDB Compass将一些数据插入到我的MongoDB API中。我的问题是,只有外部对象会自动生成一个"_id"。因此posts-ect中的嵌套对象没有"_id"。是否可以为所有对象生成id?
这是我插入的数据的演示版本:
{
"company_name":"Company name",
"columns":[
{
"name":"Opportunities",
"percentage":{
"$numberDecimal":"0"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"Prospects",
"percentage":{
"$numberDecimal":"0.25"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"Proposals",
"percentage":{
"$numberDecimal":"0.5"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"Presentations",
"percentage":{
"$numberDecimal":"0.75"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"Won",
"percentage":{
"$numberDecimal":"1"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"Lost",
"percentage":{
"$numberDecimal":"1"
},
"total":{
"$numberDecimal":"0"
}
},
{
"name":"No Opportunity",
"percentage":{
"$numberDecimal":"1"
},
"total":{
"$numberDecimal":"0"
}
}
],
"board_posts":[
{
"company_type": "Surveying",
"lines_of_business": "Strategic Advisors",
"author_id":
{
"$oid": "5ea02eaa1c9d440000911537"
},
"division": "Advisory"
},
{
"company_type": "Damage Management",
"lines_of_business": "Strategic Sales",
"author_id":
{
"$oid": "5ea02eaa1c9d440000911537"
},
"division": "Advisory"
},
{
"company_type": "Claims Management",
"lines_of_business": "Strategic Sales",
"author_id":
{
"$oid": "5ea02eaa1c9d440000911537"
},
"division": "Advisory"
}
],
"divisions":[
{
"name":"Advisory"
},
{
"name":"M&A"
},
{
"name":"Partnerships"
}
]
}
外部对象将生成一个"_id",例如:
{
"_id":{
"$oid": "5ea02eaa1c9d440000919999"
},
"company_name":"Company name",
"columns":[ objects ],
"board_posts":[ objects ],
"divisions":[ objects ]
}
但我希望为列、board_posts和divisions中的每个对象生成一个_id。
从MongoDB指南针来看这是不可能的。。。我花了很长时间寻找解决方案,最后写了一个脚本来做同样的事情。
这是的脚本要点
https://gist.github.com/bansalvks/c6b5b2bdddc18e0957e26434d165ca1d
希望这将有助于来访者:(
/**
* 1-to-many of ObjectIDs from a MongoDB Compass export...
*
* NOTE: This must be 1 line because _MONGOSH "reasons"
* NOTE: This replaces INLINE (AKA better come correct!)
* Choose a different target in $set if you want
*
* COLLECTION = your target collection
* columnWithIds = your array of foriegn keys field [$oid:ID] export
*
* MongoDB Compass=>_MONGOSH after importing field *as a string*:
*/
db.COLLECTION.find().forEach(doc=> { let columnWithIds = JSON.parse(doc.columnWithIds); db.COLLECTION.updateOne( { _id: doc._id }, { $set: { columnWithIds: columnWithIds.map(id => ObjectId(id.$oid)) }}, { upsert: true } ); })