MongoDBRef how to write a query
I'm working with the MongoDB official开发者_如何转开发 driver (10Gen). And I cannot query a MonogoDBRef propertie. I have the following classes:
public class UserData
{
private ObjectId id;
public ObjectId _id
{
get { return id; }
set { id = value; }
}
[BsonElement("Mail")]
public string Email { get; set; }
public string Name{ get; set; }
}
public class UserSettings
{
private ObjectId id;
public ObjectId _id
{
get { return id; }
set { id = value; }
}
[BsonElement("usr")]
public MongoDBRef User { get; set; }
public List<SettingsUser> Settings{ get; set; }
}
I want to make a query that having the UserData I fetch the UserSettings of that user. I try the following but it does not work:
var colletion = db.GetCollection<UserSettings>("UsrSettings");
collection.Find(Query.EQ("usr", usr._id);
also I tried this:
collection.Find(Query.EQ("usr", new MongoDBRef("UsrSettings", usr._id));
But it does not compile because MongoDBRef is not a BsonValue.
Another try:
collection.FindOne(Query.EQ("usr.$id", User._id));
And I get the exception: Unexpected element '$ref'.
Any idea? or workaround? Thanks!
Sridhar answered my question here: https://groups.google.com/forum/#!msg/mongodb-user/Tip9AQa_1TE/YAgflwJa3tAJ
The following should give you what you want (note I am using the 1.1 driver)
var refDocument = new BsonDocument {
{"$ref", "userdata"},
{"$id", usr._id}
};
var query = Query.EQ("usr", refDocument);
var result = userDataCollection.FindOne(query);
Here userdata is the name of the collection that stores user data. Having said that if all documents in the UserSettings collection always refer to only documents from the UserData collection then you should just use a manual reference as specified in http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef. DBRefs are useful for the scenario where documents in a single collection can reference documents from multiple other collections.
精彩评论