Mongodb集团成为字典式结构

时间:2016-01-04 17:22:29

标签: c# mongodb mongodb-.net-driver

假设我有以下记录:

public class Configuration {

int initialCycleTime = RobotManager.calcLowerBound();

// Holds our array of operations
private ArrayList configuration = new ArrayList<Operation>();
private ArrayList robotAssignment = new ArrayList<Robot>();
private ArrayList operationPartition = new ArrayList<Integer>();

// Cache
private int fitness = 0;

// Constructs a blank configuration
public Configuration() {
    for (int i = 0; i < OperationManager.numberOfOperations(); i++) {
        configuration.add(null);
    }

    for (int i = 0; i < GA_RALBP.numberOfStations; i++) {
        operationPartition.add(null);
    }

    for (int i = 0; i < GA_RALBP.numberOfStations; i++) {
        robotAssignment.add(null);
    }

}

// Creates a random individual
public void generateIndividual() {
    // Loop over all operations and add them to our configuration
    for (int operationIndex = 0; operationIndex < OperationManager.numberOfOperations(); operationIndex++) {
        setOperation(operationIndex, OperationManager.getOperation(operationIndex));
    }
    // Randomly shuffle the configuration
    Collections.shuffle(configuration);
}

在mongodb C#驱动程序中,如何使用此数据格式调用集合来生成类似的内容:

{ id: 1, value : 1, Date: 2016-01-01 },
{ id: 1, value : 2, Date: 2016-01-01 },
{ id: 2, value : 3, Date: 2016-01-01 },
{ id: 3, value : 4, Date: 2016-01-01 }

所以我想在“id”字段上进行分组,然后将所有按ID分组的结果作为列表返回。所以结构就像C#的

 { 
    {
      id: 1, 
      records : [
        {value : 1, Date: 2016-01-01}, 
        {value : 2, Date: 2016-01-01}
    ]}, 
   { 
      id : 2, 
      records : [{value : 3, Date: 2016-01-01}] 
   },
   { 
      id : 3, 
      records : [{value : 4, Date: 2016-01-01}] 
   }
}

1 个答案:

答案 0 :(得分:0)

刚才意识到这是一个老问题......但如果有人碰到它:

我目前还没有让mongo进行测试,但你应该可以通过linq使用聚合,例如:

var query = collection.AsQueryable()
                      .GroupBy(r => r.Id)
                      .Select(g => new { id = g.Key, records = g.Value });