Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDB Rename embedded field

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.

like image 831
John Avatar asked Aug 01 '11 16:08

John


People also ask

How do I rename a field in MongoDB?

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.

How do I rename a field in MongoDB aggregation?

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.


1 Answers

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);
like image 95
Christopher Currens Avatar answered Oct 31 '22 04:10

Christopher Currens