Mongoid, find object by searching by part of the Id? - mongodb

I want to be able to search for my objects by searching for the last 4 characters of the id. How can I do that?
Book.where(_id: params[:q])
Where the param would be something like a3f4, and in this case the actual id for the object that I want to be found would be:
bc313c1f5053b66121a8a3f4
Notice the last for characters are what we searched for. How can I search for just "part" of my objects id? instead of having my user search manually by typing in the entire id?
I found in MongoDB's help docs, that I can provide a regex:
db.x.find({someId : {$regex : "123\\[456\\]"}}) // use "\\" to escape
Is there a way for me to search using the regular mongo ruby driver and not using Mongoid?

Usually, in Mongoid you can search with a regexp like you normally would with a string in your call to where() ie:
Book.where(:title => /^Alice/) # returns all books with titles starting with 'Alice'
However this doesn't work in your case, because the _id field is not stored as a string, but as an ObjectID. However, you could add (and index) a field on your models which could provide this functionality for you, which you can populate in an after_create callback.
<shameless_plug>
Alternatively, if you're just looking for a shorter solution to the default Mongoid IDs, I could suggest something like mongoid_token which makes it pretty easy to add shorter tokens/ids to your Mongoid documents.
</shameless_plug>

Related

How to allow leading wild cards in custom smart search web part (Kentico 10)

I have a custom index for my products and I am using the Subset Analyzer. This Analyzer works great, but if you do field searches, it does not work.
For example, I have a document with the following fields:
"documentname", "My-Document-Name"
"tags", "1234,5678,9101"
"documentdescription", "This is a great Document, My-Document-Name."
When I just search "name AND tags:(1234)", I get this document in my results because it searches +_content:name.
-- However:
When I search "documentname:(name)^3.0 AND tags:(1234)", I do not get this document in my results.
Of course, when I do "documentname:(*name*)^3.0" I get a parse error saying: '*' or '?' not allowed as first character in WildcardQuery.
How can I either enable wildcard query in my custom CMS.Search webpart?
First of all you have to make sure that a field you checking is in the index with proper name. documentname might not be in the index it can be called _title, depends how you index is set up. Get lukeall and check your index (it should be in \CMS\App_Data\CMSModules\SmartSearch\YourIndexName). You can use luke to test your searches as well.
For examples there is no tags but there is documenttags field.
P.S. Wildcards are working and you are right you can't use them as a first character by default (lucene documentation says: You cannot use a * or ? symbol as the first character of a search), but there is a way to set it up in lucene.net, although i dont know if there are setting for that in Kentico. But i dont think you need wildcards, so your query should be (assuming you have documentname and documenttags in the index):
+(documentname:"My-Name" AND documenttags:"tag1")

How can you filter search by matching String to a field in Algolia?

I'm trying to create filters for a search on an Android app where a specific field in Algolia must exactly match the given String in order to come up as a hit. For example if Algolia has a field like "foo" and I only want to return hits where "foo" is equal to "bar", then I would expect that I would have to use a line of code like this:
query.setFilters("foo: \"bar\"");
Any guesses as to why this isn't working like I see in the examples or how to do so?
Ah, I thought that attributesForFaceting was done by setting what was searchable or not. It was on a different page within the dashboard than I was previously using. Thanks #pixelastic.

how to find partial search in Mongodb?

How to find partial search?
Now Im trying to find
db.content.find({$text: {$search: "Customer london"}})
It finds all records matching customer, and all records matching london.
If I am searching for a part of a word for example lond or custom
db.content.find({$text: {$search: "lond"}})
It returns an empty result. How can I modify the query to get the same result like when I am searching for london?
You can use regex to get around with it (https://docs.mongodb.com/manual/reference/operator/query/regex/). However, it will work for following :
if you have word Cooking, following queries may give you result
cooking(exact matching)
coo(part of the word)
cooked(The word containing the english root of the document word, where cook is the root word from which cooking or cooked are derived)
If you would like to go one step further and get a result document containing cooking when you type vooking (missplled V instead of C), go for elasticsearch.
Elasticsearch is easy to setup, has extremely powerful edge-ngram analyzer which converts each words into smaller weightage words. Hence when you misspell, you will still get a document based on score elasticsearch gives to that document.
You can read about it here : https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html
it will always return the empty array for partial words like when you are searching for lond to get this type of text london..
Because it take full words and search same as that they are ..
Not achive same results like :-
LO LON LOND LONDO LONDON
Here you may get help from ELASTIC-SEARCH . It is quite good for full text search when implement with mongoDB.
Refrence : ElasticSearch
Thanks
The find all is to an Array
clientDB.collection('details').find({}).toArray().then((docs) =>
I now used the str.StartWith in a for loop to pick out my record.
if (docs[i].name.startsWith('U', 0)) {
return console.log(docs[i].name);
} else {
console.log('Record not found!!!')
};
This may not be efficient, but it works for now

MongoDB - Using regex wildcards for search that properly filter results

I have a Mongo search set up that goes through my entries based on numerous criteria.
Currently the easiest way (I know it's not performance-friendly due to using wildcards, but I can't figure out a better way to do this due to case insensitivity and users not putting in whole words) is to use regex wildcards in the search. The search ends up looking like this:
{ gender: /Womens/i, designer: /Voodoo Girl/i } // Should return ~200 results
{ gender: /Mens/i, designer: /Voodoo Girl/i } // Should return 0 results
In the example above, both searches are returning ~200 results ("Voodoo Girl" is a womenswear label and all corresponding entries have a gender: "Womens" field.). Bizarrely, when I do other searches, like:
{ designer: /Voodoo Girl/i, store: /Store XYZ/i } // should return 0 results
I get the correct number of results (0). Is this an order thing? How can I ensure that my search only returns results that match all of my wildcarded queries?
For reference, the queries are being made in nodeJS through a simple db.products.find({criteria}) lookup.
To answer the aside real fast, something like ElasticSearch is a wonderful way to get more powerful, performant searching capabilities in your app.
Now, the reason that your searches are returning results is that "mens" is a substring of "womens"! You probably want either /^Mens/i and /^Womens/i (if Mens starts the gender field), or /\bMens\b/ if it can appear in the middle of the field. The first form will only match the given field from the beginning of the string, while the second form looks for the given word surrounded by word boundaries (that is, not as a substring of another word).
If you can use the /^Mens/ form (note the lack of the /i), it's advisable, as anchored case-sensitive regex queries can use indexes, while other regex forms cannot.
$regex can only use an index efficiently when the regular expression has an anchor for the beginning (i.e. ^) of a string and is a case-sensitive match.

how do i query for a mongo document using its collection attribute (acts_as_tree) using mongoid and mongo console?

here's my model:
class Person
acts_as_tree
end
i relate multiple objects as a tree:
P1
|
---
| |
P1.1 P1.2
|
---
| |
P1.1.1 P1.1.2
here if i need to retreive P1.1.1 i need to write a query that effectively asks:
get me the Person with name P1.1.1 and path (given by acts_as_tree) [P1, P1.1].
querying by just name is not enough as i can have similar named people at multiple paths.
how do i do this?
> db.people.find({name: 'P1.1.1'})
above snippet will show me the path attribute correctly as expected, but i cannot query by that path.
> db.people.find({name: 'P1.1.1', path: [{name: 'P1'}, {name: 'P1.1'}]})
doesn't work. neither does:
> db.people.find({name: 'P1.1.1', path: [db.people.find({name: 'P1'}),
db.people.find({name: 'P1.1'})]})
but that explains what i'm trying to do.
One of the ways where you can query something like as follows:
db.people.find({name : 'Joe', 'path' : { $all : [ObjectId("4e0fcf1722b7a9439200002e"), ObjectId("4e0fcf1622b7a9439200002b")]}})
However the drawback I think of this is:
You don't get to substitute the object relations/joins directly in mongo shell. You have to use the ObjectId object
The $all clause does not necessitate that the order of path is strictly same, which means that a person with name "Joe" referenced by path "hometown/town/" would come up as well as "Joe" from "tome/hometown".
I would presume that second one may be a deal breaker. Also, I am presuming that mongoid in several cases pass across the query options directly to mongodb (or atleast there are ways to do that). Hence it should be possible to do a search in ruby code using given query above.
Nevertheless, I'll do some more re-search on this and post my findings back.
Hope it helps.
Edit
To alleviate the second problem above there is also another way to query a person with a specific path. Find it below:
db.people.find({name : 'Joe', 'path.0' :ObjectId("4e0fcf1722b7a9439200002e"), 'path.1':ObjectId("4e0fcf1622b7a9439200002b")})
This would ensure that path is exactly what you are looking for. However this works in mongodb shell and you may still need to figure out, how mongoid can run an equivalent of this. Plus you may have to construct this query dynamically to create a path for person and that (for deep nested people) may just become long and ugly.
I would suggest skimming through following links on mongodb documentation to get a better understanding.
http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray
I hope this is what you were looking for.