[CSHARP-597] Using .NET Guid as mongodb document id Created: 10/Oct/12 Updated: 20/Mar/14 Resolved: 10/Oct/12 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | None |
| Affects Version/s: | 1.6 |
| Fix Version/s: | None |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Nikita Sushkov | Assignee: | Unassigned |
| Resolution: | Done | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
I'm trying to use .NET Guid as document id for my mongodb documents. The problem that I face now is that I can't fetch new document by id after insertion: MongoCollection.AsQueryable().Where(user => user.Id == id) I saw that Guid bytes are reversed in MongoDb, so I tried something like this: public TData GetById(Guid id) { var reverseId = Reverse(id); return MongoCollection.AsQueryable() .Where(user => user.Id == reverseId) as TData; }private static Guid Reverse(Guid initial) { byte[] guidBytes = initial.ToByteArray(); Array.Reverse(guidBytes, 0, 4); Array.Reverse(guidBytes, 4, 2); Array.Reverse(guidBytes, 6, 2); return new Guid(guidBytes); }Still, it does not work... Please help. |
| Comments |
| Comment by Craig Wilson [ 10/Oct/12 ] |
|
Ok, then I'm going to close this issue. |
| Comment by Nikita Sushkov [ 10/Oct/12 ] |
|
Thanks for answer, actually whong query syntax was the real problem, but when I saw reverted bytes in mongodb I thought that was the reason... |
| Comment by Craig Wilson [ 10/Oct/12 ] |
|
Are you still doing the byte reversals? That should not be necessary under any circumstances. .Where should work just fine, but it returns all the documents that match, which in this case would only be one, so you'd need to iterate to get the first doc. In this case, SingleOrDefault makes more sense, but you should never have to do any byte reversing at all. |
| Comment by Nikita Sushkov [ 10/Oct/12 ] |
|
Was my mistake. Query should look like this: _collection.AsQueryable().SingleOrDefault(user => user.Id == id) Works fine. |