【问题标题】:mongodb query to get field only in .NET codemongodb 查询仅在 .NET 代码中获取字段
【发布时间】:2014-01-28 14:40:17
【问题描述】:

谁能帮助获得以下查询的正确 .NET(C# 或 VB.NET):

> db.usercollection.find( {}, { username:1, _id: 0 } )
   { "username" : "testuser1" }
   { "username" : "testuser2" }
   { "username" : "testuser3" }

基本上我只想返回文档的某些字段。无论如何,mongodb c#驱动程序是否会将结果转换为可以填充网格(extjs网格)或图表的json格式,而无需我明确地进行转换。

 Using mongo.RequestStart(db)
        Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll()
        Dim collection3 = db.GetCollection(Of BsonDocument)("usercollection").
                        Find({}, {"username:1", "_id:0"})

collection3 行不正确。

也尝试了以下方法:

        For Each ruleSet In collection
            Dim rules As String = ruleSet.GetValue(0).AsString
            response = rules & response
        Next

但这会产生错误:

UNABLE TO CAST OBJECT OF TYPE 'MONGODB.BSON.BSONOBJECTID TO TYPE MONGODB.BSON.BSONSTRING

【问题讨论】:

    标签: .net json vb.net extjs4 mongodb-.net-driver


    【解决方案1】:

    如果要将结果限制为特定字段,则需要在 MongoCursor 上使用 SetFields,如下所示:

    MongoCursor<BsonDocument> cursor = _db.GetCollection<BsonDocument>.FindAll(); // or any other query
    cursor.SetFields("username");
    

    MongoD 使用 BSON 表示 Binary JSON。如果您想将其用作JSON,请使用扩展方法:

    BsonDocument document;
    document.ToJson();
    

    【讨论】:

    • 谢谢一百万。还有一个问题:我如何只限制用户名而不包括 _id (objectId)...d=[{ "_id" : ObjectId("52d2f2b3c60804b25bc5d2ca"), "username" : "testuser1" }, { "_id " : ObjectId("52d2f2f9c60804b25bc5d2cb"), "username" : "testuser2" }, { "_id" : ObjectId("52d2f2f9c60804b25bc5d2cc"), "username" : "testuser3" }]
    • @vbNewbie 您的意思是您只想查询用户名字段,甚至不查询该文档的_id?
    • 是的,先生。那可能吗?我需要将此数据映射到网格并希望忽略 _id。
    • 我认为最好在客户端这样做。我不确定它可以在数据库中完成。在这里:cursor.Select(document =&gt; document["username"])
    • 你的意思是把我需要的数据从结果集中分开?
    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2017-07-30
    相关资源
    最近更新 更多