i want to create a new field named “index” from an existing field named “id” in my MongoDB collection.
This is how my documents looks:
{
"_id": {
"$oid": "6536e62e619aa9d8e2cc82f7"
},
"name": "Thomas Bayes",
"bithplace": "Londres",
"institution": "Universidad de Edimburgo",
"topics": [
"teología",
"estadística bayesiana"
],
"maininterest": "Estadística Bayesiana",
"img": "https://live.staticflickr.com/65535/53272747904_a07cba4990_n.jpg",
"id": "1",
}
I tried db.getCollection("stats").updateMany( { }, { $set: { "$index": "$id"}} )
But i get index = “$id”, not the value of the key id… can you help me to achieve that? thank you
Jason_Tran
(Jason Tran)
3
Based off the sample document you provided, do you want to have the "index" field with a value of 1?
I tried something similar in my test environment, you can see below:
testdb> db.coll.find()
[
{
_id: ObjectId("6552da8f81ae04007d21a860"),
name: 'Thomas Bayes',
bithplace: 'Londres',
institution: 'Universidad de Edimburgo',
topics: [ 'teología', 'estadística bayesiana' ],
maininterest: 'Estadística Bayesiana',
img: 'https://live.staticflickr.com/65535/53272747904_a07cba4990_n.jpg',
id: '1' /// <--- id value of '1'
}
]
Query and output:
/// Query
testdb> db.coll.updateMany( { }, [{ $set: { "index": "$id"}}] )
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
/// Output
testdb> db.coll.find()
[
{
_id: ObjectId("6552da8f81ae04007d21a860"),
name: 'Thomas Bayes',
bithplace: 'Londres',
institution: 'Universidad de Edimburgo',
topics: [ 'teología', 'estadística bayesiana' ],
maininterest: 'Estadística Bayesiana',
img: 'https://live.staticflickr.com/65535/53272747904_a07cba4990_n.jpg',
id: '1',
index: '1' /// <--- index field now exists with a value of '1'
}
]
See if this works for your use case and requirements on a test environment first before trying this out on production.
Regards,
Jason
1 Like
system
(system)
Closed
4
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.