DWQA QuestionsCategory: ProgramC ා failed to get the objectid of mongodb and map it to the object
SSS turbidity current asked 4 months ago

Get the bson from mongodb aggregation. Now I want to convert this bson into an entity object
However, objectid can’t be converted all the time. I hope you can solve your puzzles
How can bson be bound to a custom object
Or, how to convert the obtained objectid to string
be deeply grateful
Second, when the object ID is converted to the object, I will be prompted to convert to the entity
1. This is the result of aggregation and acquisition

        List<BsonDocument> pipe = mRoot.answerRecord.GetAggregate()
            .Match(x => x.userId == userId && x.subjectId == subjectId)
            .Match(x => x.correct == 0 || x.correct == 1)
            .Sort(BsonDocument.Parse("{ 'mtime' : -1 }"))
            .Lookup("question", "questionId", "_id", "question")
            .Skip(pageSize * (page - 1))

2. This is my attempt to traverse and convert to entity object
`foreach(var p in pipe)

                //Some questions about todo objectid conversion
                var j = p.ToJson();
                ErrorRecordsResult r = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorRecordsResult>(j);

3. Entity object
`public class ErrorRecordsResult

    public ObjectId _id { get; set; }

    public int cate; 
2 Answers
Then go hiking answered 4 months ago

What do you useMongoDB.BsonThis library? directToString()Isn’t it over?

Supplement for comment area:

SSS turbidity current replied 4 months ago

Thanks to Daniel’s busy schedule, but after toString and tojson, the results are {“_ ID “: objectid (” 5e75e9cb654a00000db005172 “),” CTime “: 2001}, when I convert objects through jsonconvert, objectid fails.

Then go hiking replied 4 months ago

@SSS turbidity currentI understand what you mean, because you use the wrong object. Objectid is bson, not standard JSON. You should not use itNewtonsoft.Json.JsonConvertInstead of deserializing, you should useMongoDB.Bson.Serialization.BsonSerializer。 Here’s an example. It’s posted under the original answer.

SSS turbidity current replied 4 months ago

Thank you very much. I’ve sponsored a cup of happy water for the boss. Have you received it

No trace of desire answered 4 months ago

In fact, it can be directly converted to the specified class object without first converting it to the bsondocument

SSS turbidity current replied 4 months ago

Which way is it used