2

I'm trying to deserialize filter with LUUID (or NUUID in this example) to BsonDocument:

var tmpQry = "{'ValueId': NUUID('ca7ac84f-18bf-42f0-b028-333ed144c549')";
var tmpBson = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(tmpQry);

and getting an error:

System.FormatException: 'JSON reader was expecting a value but found 'NUUID'.'

I understand, that LUUID is not valid for JSON, but is it somehow possible to get BsonDocument from my string?

In my particular case i can't implement MongoDB nested $elemMatch query, like in this issue. But my query contains identifiers:

db.getCollection('my_db').aggregate([
    {
        $match: {
            'Event.key_attributes': {
                $all: [
                    { '$elemMatch': { 'Type.Code': 'code1', 'ValueId': LUUID('00000000-0000-0000-0000-000000000001') } },
                    { '$elemMatch': { 'Type.Code': 'code2', 'ValueId': LUUID("00000000-0000-0000-0000-000000000002") } },
                    { '$elemMatch': { 'Type.Code': 'code3', 'ValueId': LUUID("00000000-0000-0000-0000-000000000003") } }
                ]
            }
        }
    },
    {
        $group: {
            '_id': '$$CURRENT.Event.type._id',
            'code': { '$last': '$$CURRENT.Event.type.Code' },
            'value': { '$sum': '$$CURRENT.Event.value' }
        }
    }
]);

, and I even can't deserialize it into a BsonDocument. Does my problem have any solution? Thanks a lot.

2 Answers2

0

Finally, I solved this issue. Instead of trying to serialize the query from a string, I created BsonDocument pipeline:

var filter = new BsonDocument {{
    "$match", new BsonDocument {{
        "Event.key_attributes", new BsonDocument {{
        "$all", new BsonArray().AddRange(limit.KeyAttributes.Select(ka => new BsonDocument(
            "$elemMatch", new BsonDocument().AddRange(new List<BsonElement>{
            new BsonElement("Type.Code", ka.Type.Code),
            new BsonElement("ValueId", ka.ValueId)
            })
        )).ToList())
        }}
    }}
}};


var group = new BsonDocument {{
    "$group", new BsonDocument().AddRange(new List<BsonElement>{
        new BsonElement("_id", "$$CURRENT.Event.type._id"),
        new BsonElement("code", new BsonDocument{{
            "$last", "$$CURRENT.Event.type.Code" }}),
        new BsonElement("value", new BsonDocument{{
            "$sum", "$$CURRENT.Event.value" }})
    })
}};

var pipeline = new BsonDocument[]
{
    filter,
    group
};

var result = collection.Aggregate<MyOutputClass>(pipeline).ToListAsync();

There were no problems with Guid.

0

The poster has worked around his problem, but for those happening up this question later: Use CSUUID('guid-string-here') for the CSharp legacy format.

adhominem
  • 1,104
  • 9
  • 24