![](/img/trans.png)
[英]Mongodb C# driver - Update document then select collection with updated document
[英]Select all _id from mongodb collection with c# driver
我在mongodb中有大型文档集,并且只想获得_id列表。 Mongodb查询是db.getCollection('Documents').find({},{_id : 0, _id: 1})
。 但是在C#查询中
IMongoCollection<T> Collection { get; set; }
...
List<BsonDocument> mongoResult = this.Collection.FindAsync(FilterDefinition<T>.Empty, new FindOptions<T, BsonDocument>() { Projection = "{ _id: 0, _id: 1 }" }).Result.ToList();
throw exeption InvalidOperationException: Duplicate element name '_id'.
我想只获得_id列表,不需要其他文件。 文档可能具有不同的结构,并且排除所有其他文件,这些文件很难。
什么C#查询对应于指定的mongodb查询db.getCollection('Documents').find({},{_id : 0, _id: 1}
?
更新:不提供与服务器相关的查询大量数据的解决方案,例如
this.Collection.Find(d => true).Project(d => d.Id).ToListAsync().Result;
由于您使用C#驱动程序,我建议使用AsQueryable
然后使用linq。
在我看来,它更好,因为你不需要魔法字符串,你将从你的linq知识中受益。 然后它看起来像这样
database.GetCollection<T>("collectionname").AsQueryable().Select(x => x.Id);
阿列克谢是正确的,这些解决方案
var result = (await this.Collection<Foos>
.Find(_ => true)
.ToListAsync())
.Select(foo => foo.Id);
将通过网络拉出整个文档集合,反序列化,然后将Lin中的Id
映射到对象,这将是非常低效的。
诀窍是在使用.ToListAsync()
执行查询之前使用.Project
只返回_id
键。
如果您不想使用强类型DTO反序列化,则可以将类型指定为原始BsonDocument
。
var client = new MongoClient(new MongoUrl(connstring));
var database = client.GetDatabase(databaseName);
var collection = database.GetCollection<BsonDocument>(collectionName);
var allIds = (await collection
.Find(new BsonDocument()) // OR (x => true)
.Project(new BsonDocument { { "_id", 1 } })
.ToListAsync())
.Select(x => x[0].AsString);
其执行类似于以下的查询:
db.getCollection("SomeCollection").find({},{_id: 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.