[英]Select all _id from mongodb collection with c# driver
I have large document collection in mongodb and want to get only _id list. 我在mongodb中有大型文档集,并且只想获得_id列表。 Mongodb query is
db.getCollection('Documents').find({},{_id : 0, _id: 1})
. Mongodb查询是
db.getCollection('Documents').find({},{_id : 0, _id: 1})
。 But in C# query 但是在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'.
throw exeption
InvalidOperationException: Duplicate element name '_id'.
I want to get only _id list, other fileds not needed. 我想只获得_id列表,不需要其他文件。 Documents may have different structures and exclude all other fileds manualy difficult.
文档可能具有不同的结构,并且排除所有其他文件,这些文件很难。
What C# query corresponds to the specified mongodb query db.getCollection('Documents').find({},{_id : 0, _id: 1}
? 什么C#查询对应于指定的mongodb查询
db.getCollection('Documents').find({},{_id : 0, _id: 1}
?
UPDATE: Do not offer solutions related query large amounts of data from the server, for example like 更新:不提供与服务器相关的查询大量数据的解决方案,例如
this.Collection.Find(d => true).Project(d => d.Id).ToListAsync().Result;
Since your using C# driver I would recommend to use the AsQueryable
and then use linq instead. 由于您使用C#驱动程序,我建议使用
AsQueryable
然后使用linq。
In my opinion it is better since you wouldn't need the magic strings and you would benefit from your linq knowledge. 在我看来,它更好,因为你不需要魔法字符串,你将从你的linq知识中受益。 Then it would look something like this
然后它看起来像这样
database.GetCollection<T>("collectionname").AsQueryable().Select(x => x.Id);
Alexey is correct, solutions such as these 阿列克谢是正确的,这些解决方案
var result = (await this.Collection<Foos>
.Find(_ => true)
.ToListAsync())
.Select(foo => foo.Id);
Will pull the entire document collection over the wire, deserialize, and then map the Id
out in Linq To Objects, which will be extremely inefficient. 将通过网络拉出整个文档集合,反序列化,然后将Lin中的
Id
映射到对象,这将是非常低效的。
The trick is to use .Project
to return just the _id
keys, before the query is executed with .ToListAsync()
. 诀窍是在使用
.ToListAsync()
执行查询之前使用.Project
只返回_id
键。
You can specify the type as a raw BsonDocument
if you don't want to use a strongly typed DTO to deserialize into. 如果您不想使用强类型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);
Which executes a query similar to: 其执行类似于以下的查询:
db.getCollection("SomeCollection").find({},{_id: 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.