Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all _id from mongodb collection with c# driver

I have large document collection in mongodb and want to get only _id list. Mongodb query is db.getCollection('Documents').find({},{_id : 0, _id: 1}). But in C# query

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'. I want to get only _id list, other fileds not needed. 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}?

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;
like image 410
Alexey Avatar asked Nov 18 '16 08:11

Alexey


People also ask

How do I retrieve all files from a collection in MongoDB?

Connect to a database using the getDatabase() method. Get the object of the collection from which you want to retrieve the documents, using the getCollection() method. Retrieve the iterable object containing all the documents of the current collection by invoking the find() method.

How do I select a single field for all documents in a MongoDB collection?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I query a collection in MongoDB?

Use the db. collection. find() method in the MongoDB Shell to query documents in a collection.

Which query object selects all documents in a MongoDB collection?

A compound query can specify conditions for more than one field in the collection's documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query selects the documents in the collection that match all the conditions.


1 Answers

Since your using C# driver I would recommend to use the AsQueryable and then use linq instead.

In my opinion it is better since you wouldn't need the magic strings and you would benefit from your linq knowledge. Then it would look something like this

database.GetCollection<T>("collectionname").AsQueryable().Select(x => x.Id);
like image 116
SJFJ Avatar answered Sep 23 '22 12:09

SJFJ