Mongodb - 使用c#驱动程序包含或排除某些元素

时间:2011-12-09 16:01:04

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

如何将此mongo查询转换为C#中的Query.EQ语句?

db.users.find({name: 'Bob'}, {'_id': 1});

换句话说,我不希望一切都返回到C# - 只需要我需要的一个元素,即_id。与往常一样,Mongo C# Driver tutorial没有帮助。

4 个答案:

答案 0 :(得分:39)

更新:使用新的驱动程序版本(1.6+),您可以使用linq避免字段名称硬编码:

var users = usersCollection.FindAllAs<T>()
                           .SetFields(Fields<T>.Include(e => e.Id, e => e.Name));

你可以通过mongodb cursor的SetFields方法来实现:

var users = usersCollection.FindAllAs<T>()
                 .SetFields("_id") // include only _id
                 .ToList();

默认情况下,SetFields包含指定的字段。如果您需要排除某些字段,可以使用:

var users = usersCollection.FindAllAs<T>()
                 .SetFields(Fields.Exclude("_id")) // exclude _id field
                 .ToList();

或者你可以一起使用它们:

var users = usersCollection.FindAllAs<T>()
                 .SetFields(Fields.Exclude("_id")   // exclude _id field
                                  .Include("name")) // include name field
                 .ToList();

答案 1 :(得分:29)

从驱动程序的v2.0开始,有一个新的async-only API。不应再使用旧的API,因为它是新API的阻止外观,不推荐使用。

目前推荐的包含或排除某些成员的方法是使用Project来自IFindFluent的{​​{1}}方法。

您可以传递lambda表达式:

Find

或使用投影构建器:

var result = await collection.Find(query).Project(hamster => hamster.Id).ToListAsync();

var result = await collection.Find(query)
    .Project<Hamster>(Builders<Hamster>.Projection.Include(hamster => hamster.Id))
    .ToListAsync();

答案 2 :(得分:1)

更新您可以使用投影和FindAsync which returns a cursor and doesn't load all documents at once unlike Find。您还可以设置排序顺序并限制返回的文档数。

    var findOptions = new FindOptions<BsonDocument>();

    findOptions.Projection = "{'_id': 1}";

    // Other options
    findOptions.Sort = Builders<BsonDocument>.Sort.Ascending("name");           
    findOptions.Limit = int.MaxValue;

    var collection = context.MongoDatabase.GetCollection<BsonDocument>("yourcollection");   

    using (var cursor = collection.FindSync("{name : 'Bob'}", options))
    {
        while (cursor.MoveNext())
        {
            var batch = cursor.Current;
            foreach (BsonDocument document in batch)
            {
                // do stuff...
            }
        }
    }

答案 3 :(得分:0)

这是一种根据需要仅检索Option Explicit Sub paste_to_table() Dim last_tblrow As Double Dim tblwks As Worksheet, newwks As Worksheet, sh As Worksheet Dim targetrng As Range Dim newname As String Dim wb As Workbook: Set wb = ThisWorkbook Dim ws As Worksheet: Set ws = wb.Sheets("Player Template") Set tblwks = ThisWorkbook.Worksheets("Table") Dim query As Long, xst As Boolean, info As String retry: xst = False newname = Application.InputBox("Please Enter New players Name.", info, , , , , , 2) If newname = "False" Then Exit Sub For Each sh In wb.Sheets If sh.Name = newname Then xst = True: Exit For End If Next If Len(newname) = 0 Or xst = True Then info = "Name is invalid. Please Retry." GoTo retry End If ws.Copy After:=ws: Set newwks = ActiveSheet: newwks.Name = newname 'get last row of "table" column "C" last_tblrow = tblwks.Cells(Rows.Count, "C").End(xlUp).Row 'set targetrng range variable to next empty cell of column C Set targetrng = tblwks.Range("C" & last_tblrow + 1) 'newname value into next empty row of column C targetrng.Value = newname 'next value into "D7" to of "table" wks from cell "I3","I4","I5"..... targetrng.Offset(0, 1).Value = "=" & newwks.Name & "!" & newwks.Cells(3, 9).Address targetrng.Offset(0, 2).Value = "=" & newwks.Name & "!" & newwks.Cells(3, 10).Address targetrng.Offset(0, 3).Value = "=" & newwks.Name & "!" & newwks.Cells(3, 11).Address targetrng.Offset(0, 4).Value = "=" & newwks.Name & "!" & newwks.Cells(3, 12).Address targetrng.Offset(0, 5).Value = "=" & newwks.Name & "!" & newwks.Cells(3, 13).Address End Sub 的简单方法:

id

请注意,上面的代码正在使用名为MongoDB.Entities的mongodb包装器库