I have Added text index on my collection. I am trying to filter the data with text search with some additional filters. But It is not working well with other filters.
{$text:{$search:"test"},Type:"5"}
The above query returns all 42 entries matching the criteria from mongoDB Atlas.
But when I am doing this from c# I think I am querying it wrong. What am I missing here.
var collection = db.GetCollection<TestTbl>("TestTbl");
var filter = Builders<TestTbl>.Filter.Text(searchtext)
&Builders<TestTbl>.Filter.Eq("TypeID", TypeID);
var data = collection.Find(filter).ToList();
here data is returned null.
When I am giving text only in the filter it works fine.
{$text:{$search:"test"}}
var collection = db.GetCollection<TestTbl>("TestTbl");
var filter = Builders<TestTbl>.Filter.Text(searchtext);
var data = collection.Find(filter).ToList();
The Error was with my model it was Guid Type forgot to mention the bsontype string for the field representation
Related
i have the following problem, i filtered the collection to get the specific document in collection which i need. The document inside it has some variable with some values. How do i grab the specific variable and its value from the specific document.
MongoClient client = new MongoClient();
var db = client.GetDatabase("myfirstdb");
var collection = db.GetCollection<PlayerInfo>("players");
var filter = Builders<PlayerInfo>.Filter.Eq("playerName", player.Name);
//find in document filter the parameter "isAdmin" and grab its value.
This is how my document looks like.
You have to use Project clause when you perform the find operation on the filter. Below code will do.
bool isAdmin = collection.Find(filter).Project(x => x.isAdmin).FirstOrDefault();
I am using sorting in my application and using cosmos mongodb api as database. I have created wildcard index in the code to accommodate the sorting but somehow I am still getting the error as compound index is missing. Here is how I am creating the index.
var wcIndex = new IndexKeysDefinitionBuilder<T>().Wildcard();
var wcIndexModel = new CreateIndexModel<T>(wcIndex, options);
_collection = _database.GetCollection<T>(_collectionName);
_collection.Indexes.CreateOneAsync(wcIndexModel);
and the error am getting is
The index path corresponding to the specified order-by item is
excluded / The order by query does not have a corresponding composite
index that it can be served from.
Is there anyway I can add composite index for model to get the sorting done ?
I have added the below code to make it work for using sorting in mongo Cosmos API.
IndexKeysDefinition<T> keys = "{'$**': 1}";
var wildcardIndex = new CreateIndexModel<T>(keys);
_collection = _database.GetCollection<T>(_collectionName);
_collection.Indexes.CreateOne(wildcardIndex);
I'm using the last driver. My documents are of the form
{
"ItemID": 292823,
....
}
First problem: I'm attempting to get a list of all the ItemIDs, and then sort them. However, my search is just pulling back all the _id, and none of the ItemIDs. What am I doing wrong?
var f = Builders<BsonDocument>.Filter.Empty;
var p = Builders<BsonDocument>.Projection.Include(x => x["ItemID"]);
var found= collection.Find(f).Project<BsonDocument>(p).ToList().ToArray();
When I attempt to query the output, I get the following.
found[0].ToJson()
"{ \"_id\" : ObjectId(\"56fc4bd9ea834d0e2c23a4f7\") }"
It's missing ItemID, and just has the mongo id.
Solution: I messed up the case. It's itemID, not ItemID. I'm still having trouble with the sorting.
Second problem: I tried changing the second line to have x["ItemID"].AsInt32, but then I got an InvalidOperationException with the error
Rewriting child expression from type 'System.Int32' to type
'MongoDB.Bson.BsonValue' is not allowed, because it would change the
meaning of the operation. If this is intentional, override
'VisitUnary' and change it to allow this rewrite.
I want them as ints so that I can add a sort to the query. My sort was the following:
var s = Builders<BsonDocument>.Sort.Ascending(x => x);
var found= collection.Find(f).Project<BsonDocument>(p).Sort(s).ToList().ToArray();
Would this be the correct way to sort it?
Found the solution.
//Get all documents
var f = Builders<BsonDocument>.Filter.Empty;
//Just pull itemID
var p = Builders<BsonDocument>.Projection.Include(x => x["itemID"]);
//Sort ascending by itemID
var s = Builders<BsonDocument>.Sort.Ascending("itemID");
//Apply the builders, and then use the Select method to pull up the itemID's as ints
var found = collection.Find(f)
.Project<BsonDocument>(p)
.Sort(s)
.ToList()
.Select(x=>x["itemID"].AsInt32)
.ToArray();
I have to following code to query from dynamodb
Search search = table.Query(new QueryOperationConfig { Filter = filter, AttributesToGet = list of attributes});
I can see there is data in search by expanding its node while debugging, but could not find an easy way to get the items key and values directly.
I tried with
List<Document> documentSet = new List<Document>();
do
{
documentSet = search.GetNextSet();
foreach (var document in documentSet)
{
HttpContext.Current.Response.Write(document["columnName"]);
HttpContext.Current.Response.Write(document["columnName"]);
}
} while (!search.IsDone);
Is there any direct way to get the keys and value from Search object in json or table any in any thing?
Thanks
Given an individual Document (in your case, the document object), you can call document.ToJson() or document.ToJsonPretty() to retrieve the JSON representation of the document. This blog post provides more details.
how can I insert a document inside another document with mongodb ?
I've tried something like the code below but I always have a problem converting my list of setting in the field Settings:
var settingViewModels = new[]{ setting };
var query = Query.EQ("Name", applicationName);
var update = Update.AddToSet("Settings", BsonArray.Create(setting));
db.Collection<Applications>().Update(query, update, UpdateFlags.Upsert, SafeMode.True)
I got an error when I convert my settingViewModels into BsonArray saying:
.NET type MyProject.SettingViewModel cannot be mapped into BsonType.Array
Parameter name: value
Any idea ?
thanks
John
If you want add setting item to the Settings[] array of Application collection you should use ToBsonDocument() extention method from MongoDB.Bson namespace:
var update = Update.AddToSet("Settings", setting.ToBsonDocument());
You no need create BsonArray.