Reputation: 292
Took a job recently where they use Mongo. I come from an SQL background. I'm so frustrated with even the basics of Mongo. You're my last resort before I beg to switch.
I have a collection with one document in it. The document currently has two arrays in it, but it will hold many more. I simply want to add a value to either of these arrays. (Using C#)
Is that an update or simply an add? I've not been successful in finding any solution even close to solving this.
The most success I have had so far is returning the entire collection. Like this:
var corrosion = collection.Find(new BsonDocument()).ToList();
I suppose I could create a new JSON file, add my value to it, then try and upload back into mongo, but that seems like way more work then necessary.
Is there a way to take a string value and add that to either of these arrays ?
{"_id":{"$oid":"Random nums and lets"},
"FreeCr":[
"Add New",
"4130 ",
"1008 ",
"AA70",
"AA2",
"AA6",
"EN9"
],"GalCr":[
"Add New",
"AA7 / A286",
"AAT6 / 316SS",
"AA / Ti6-4",
"AA / 4130 Steel",
"AA / CFRP",
"AA / A286",
"AA / Ti6-4",
"AA / 4130 Steel",
"AA / Ti6-4",
"316SS",
"1008 Steel"
]
}
Your help is so very much appreciated.
Upvotes: 2
Views: 525
Reputation: 725
It is more of an update. Mongo still has CRUD operations. Assuming you have a CorrosionModel similiar to this:
public class CorrosionModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId Id { get; set; }
public List<string> FreeCr { get; set; }
public List<string> GalCr { get; set; }
}
Try this:
List<CorrosionModel> corrosion = collection.Find(new BsonDocument()).ToList(); //get your model
List<string> curList = corrosion[0].FreeCr; //modify your model
curList.Add("NEW VALUE2!");
//update Mongo
var filter = Builders<CorrosionModel>.Filter.Eq("Id", corrosion[0].Id);
collection.ReplaceOne(filter, corrosion[0], new ReplaceOptions { IsUpsert = true });
Upvotes: 1