how do we rename embedded fields using C# with mongoDB ? An example of document Person would be:
{
Id: 1,
LastName: "Smith",
FirstName: "John",
Orders: {
Id: 1,
Name: "Trousers" // I want to rename **Name** into **Something**
}
}
With mongoDB syntax, it would be something like
db.Users.update({}, {$rename:{"Orders.Name":"Orders.Something"}},true, true)
Thanks.
The $rename operator updates the name of a field and has the following form: {$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } } The new field name must differ from the existing field name. To specify a <field> in an embedded document, use dot notation.
Whatever the reason, you can use the $project aggregation pipeline stage to rename a field in your query results. In some ways, this is comparable to using an alias in SQL, as it doesn't rename the underlying fields, it simply renames them in the query results.
Look at
MongoDB.Driver.Builders.Update.Rename(string oldElementName,
string newElementName)
It returns an IUpdateQuery, which you can pass to collection.Update() and rename your field. The C# Update builder has every special command you can use in mongo as a callable function to build your query.
The Builders namespace is a great namespace in the MongoDB C# driver. It includes Query and Update builders. You can chain commands and do things like this:
Update.Set("indexsize", indexSize).Set("extractsize", extractedFileSize);
or
Query.GT("filesize", 200000).In(bsonArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With