Good Morning,
I have a Issue With MongoDb, i'm trying to unset an index of "citations", on my Json you can see 1 field citations with 2 citation : "Saisir ou Selection une citations" and "XD", i'd like to unset XD, how can i achieve this ?
{
"_id" : ObjectId("604ca13de0059b65e4e67c01"),
"username" : "LOL",
"pass" : "LOL",
"citations" : [
[
{
"body" : "Saisir ou Selection une citations",
"author" : "author",
"oeuvre" : "oeuvre",
"annee" : NumberInt(1)
}
],
[
{
"body" : "XD",
"author" : "XD",
"oeuvre" : "XD",
"annee" : NumberInt(3)
}
]
]
}
I've tried Many things :
db.getCollection("Users").update(
{}, {$unset : {"citations.$.body" : "XD"}}
)
and I tried many other variant but i didnt found the right Solution.
PS :
I'm working on a C# Wpf APP, it's would be perfect if you can help me on this langage but otherwise no worries it is not very different
In update function you need to give first conditition. Than you may need to use "$pull" for removing values from array.
It should be something like this:
db.getCollection("Users").update(
{citations.body: "XD"}, {$pull : {"citations.$.body" : "XD"}}
)
you will have to use the ElemMatch and PullFilter operators in the c# driver to achieve your goal like so:
var filter = Builders<User>.Filter.ElemMatch(
u => u.Citations,
c => c.Body == "XD");
var update = Builders<User>.Update.PullFilter(
u => u.Citations,
c => c.Body == "XD");
await userCollection.UpdateManyAsync(filter, update);
here's another less verbose way to do the same thing using MongoDB.Entities library (which i wrote):
using MongoDB.Entities;
using System.Linq;
using System.Threading.Tasks;
namespace TestApplication
{
public class User : Entity
{
public Citation[] Citations { get; set; }
}
public class Citation
{
public string Body { get; set; }
}
public static class Program
{
private static async Task Main()
{
await DB.InitAsync("test");
await new[] {
new User {
Citations = new[]
{
new Citation { Body = "Saisir ou Selection une citations"},
new Citation { Body = "XD"},
}
},
new User {
Citations = new[]
{
new Citation { Body = "Saisir ou Selection une citations"},
new Citation { Body = "XD"},
}
}
}.SaveAsync();
await DB.Update<User>()
.Match(u => u.Citations.Any(c => c.Body == "XD"))
.Modify(f => f.PullFilter(u => u.Citations, c => c.Body == "XD"))
.ExecuteAsync();
}
}
}