MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come interrogare/aggiornare un sottodocumento in MongoDB usando il driver C#

1)

QueryComplete = Query.EQ(_id, "2012_11_10");
DayData myData = db.GetCollection<DayData>("DayDataCollection").FindOne(query);
// As HourData is the class member you can retrieve it from the instance of the DayData:
HourData myHour = myData.HR1;

2)

QueryComplete = Query.EQ(_id, "2012_11_10");
UpdateBuilder update = Update.Inc("HR1.Count", 1);
db.GetCollection<DayData>("DayDataCollection").Update(query, update, SafeMode.True)

;

3) Nel tuo caso devi semplicemente recuperare l'istanza DayData e quindi sommare tutti i valori necessari in modo esplicito:

QueryComplete = Query.EQ(_id, "2012_11_10");
DayData myData = db.GetCollection<DayData>("DayDataCollection").FindOne(query);
// As HourData is the class member you can retrieve it from the instance of the DayData:
int sum = myData.HR1.Count + myData.HR2.Count + ... + myData.HR24.Count;

Ma non è elegante. Se vuoi la soluzione elegante devi trasformare i tuoi campi nell'array come:

DayData
{
HR:
[{
Count: 1,
Data: "Hour 1 data"
},
{
},
...
]
}

e funziona come con l'array. Fammi sapere se è possibile trasformarlo in un array.

4) Nel tuo caso, ancora una volta, non esiste una soluzione elegante. Quello che puoi fare è sufficiente scorrere i tuoi campi e creare un array:

int[] Counts = new int[24];
Counts[0] = myData.HR1.Count;
...

Oppure puoi creare un enumeratore direttamente nella classe, ma penso che sia eccessivo nel tuo caso.