MongoDB search error - mongodb

I use mongoDB (version 3.0.2) for my application and if I will search for a User named "Hannes" than I get the following error above.
db.User.find() works without any problems.
Does anyone know what the problem is?
Thanks a lot!
db.User.find({$text:{$search:'Hannes'}})
Error: error: {
"$err" : "Unable to execute query: error processing query: ns=apoSoftDatabase.User limit=0 skip=0\nTree: TEXT : query=Hannes, language=, tag=NULL\nSort: {}\nProj: {}\n planner returned error: need exactly one text index for $text query",
"code" : 17007
}
[EDIT]
This is my document structure:
db.User.insert({ "_id" : ObjectId("5589929b887dc1fdb501cdbf"), "_class" : "com.smartinnotec.aposoft.dao.domain.User", "title" : "", "firstname" : "Claudia", "surname" : "Amreiter", "birthdate" : ISODate("1989-06-02T03:43:43.124Z"), "sex" : "FEMALE", "telephone" : "0664 / 342233223", "email" : "claudia.amreiter#aon.de", "username" : "claudia", "password" : "claudiapw", "address" : { "_id" : null, "street" : "strasse 21a", "postalCode" : 58441, "region" : "village", "country" : "Germany" }})

The "error" is because uou don't have a "text" index on your collection and you need one to use the $text operator in queries.
Create a text index
Your document may have fields like:
{
"a": "sam",
"b": "wise"
}
You can then create a "text index" over all or just a single field with something like:
db.collection.createIndex({ "a": "text", "b": "text" })
Then you can query with:
db.collection.find({ "$text": { "$search": "sam wise" } })
Or any other valid combination without problem.

I don't know the field name of your collection, however you can try this:
Try db.User.find({[field name]:'Hannes'})

Related

MongoDB: How to query nested array specific elements?

I've a complex collection in MongoDB. In this, I want to query departments data based on the subDeptName. I used query like below db.getCollection('users').find({"departments.subDeptName" : "Java"}), but its fetching all the array elements of the department. I only wants to query such department where "subDeptName" : "Java". How can we do that ?
{
"firstName" : "John",
"lastName" : "Kerr",
"email" : "john.kerr#gmail.com",
"countryName" : "USA",
"usRestrictionSw" : "N",
"status" : "Active",
"effDate" : ISODate("2012-08-24T01:46:33.000Z"),
"departments" : [
{
"subDeptCd" : "AB",
"languageCd" : "en",
"desc" : "Development Group",
"subDeptName" : "Java",
"status" : "Active"
},
{
"subDivisionAlpha2Cd" : "KG",
"subDivisionCd" : "B",
"languageCd" : "ru",
"desc" : "Testing Group",
"subDeptName" : "Python",
"status" : "Active"
},
..........
..........
..........
..........
}
}
db.getCollection('users').find({"departments.subDeptName" : "Java"})
Will match all users with a sub deperament java.
Easiest way to achieve the result you want is this:
db.getCollection('users').aggregate([
{
$unwind: "$departments"
},
{
$match: {
"departments.subDeptName" : "Java"
}
])
Now you can also add a $project phase to get only the specific fields you want.
Try this:-
db.getCollection('users').find({"departments.subDeptName" : "Java"})
i have checked this on command line work fine.
Please check your mongo version and mongo shell version
mongod --version (check mongo version)
mongo --version // check mongo shell version.
And also check error log for have unother issue.

MongoDB count occurances of a substring in a collection

Hello I'm a MongoDb beginner. I have a database of a IRC chatlog. The document structure is very simple
{
"_id" : ObjectId("000"),
"user" : "username",
"message" : "foobar foobar potato idontknow",
"time" : NumberLong(1451775601469)
}
I have thousands of these and I want to count the number of occurrences of the string "foobar". I have googled this issue and found something about aggregations. I looks very complicated and I haven't really found any issue this "simple". I'd be glad if someone pointed me in the right direction what to research and I wouldn't mind an example command that does exactly this what I want. Thank you.
There is no any built-in operator to solve your request.
You can try this query, but it has very poor performance:
db.chat.find().forEach(function(doc){
print(doc["user"] + " > " + ((doc["message"].match(/foobar/g) || []).length))
})
If you could change your message field to array, then we could apply aggregation...
EDIT:
If you add array of splitted words into your entry, we can apply aggregation
Sample:
{
"_id" : ObjectId("569bb7040586bcb40f7d2539"),
"user" : "username",
"fullmessage" : "foobar foobar potato idontknow",
"message" : [
"foobar",
"foobar",
"potato",
"idontknow"
],
"time" : NumberLong(1451775601469)
}
Aggregation. We create new entry for each array element, match given word (foobar, in this case) and then count matched result.
db.chat.aggregate([
{"$unwind" : "$message"},
{"$match" : {"message" : {"$regex" : "foobar", "$options" : "i"}}},
{"$group" : {_id:{"_id" : "$_id", "user" : "$user", "time" : "$time", "fullmessage" : "$fullmessage"}, "count" : {$sum:1}}},
{"$project" : {_id:"$_id._id", "user" : "$_id.user", "time" : "$_id.time", "fullmessage" : "$_id.fullmessage", "count" : "$count"}}
])
Result:
[
{
"_id" : ObjectId("569bb7040586bcb40f7d2539"),
"count" : 2,
"user" : "username",
"time" : NumberLong(1451775601469),
"fullmessage" : "foobar foobar potato idontknow"
}
]

How can I use mongodb projections with Go and mgo?

I am currently trying to extract a single object within a document array inside of mongodb.
This is a sample dataset:
"_id" : ObjectId("564aae61e0c4e5dddb07343b"),
"name" : "The Races",
"description" : "Horse races",
"capacity" : 0,
"open" : true,
"type" : 0,
"races" : [
{
"_id" : ObjectId("564ab9097628ba2c6ec54423"),
"race" : {
"distance" : 3000,
"user" : {
"_id" : ObjectId("5648bdbe7628ba189e011b18"),
"status" : 1,
"lastName" : "Miranda",
"firstName" : "Aramys"
}
}
},
{
"_id" : ObjectId("564ab9847628ba2c81f2f34a"),
"bet" : {
"distance" : 3000,
"user" : {
"_id" : ObjectId("5648bdbe7628ba189e011b18"),
"status" : 1,
"lastName" : "Miranda",
"firstName" : "Aramys"
}
}
},{...}
]
I can successfully query using the following in mongo:
db.tracks.find({"_id": ObjectId("564aae61e0c4e5dddb07343b")}, {"races": { $elemMatch: {"_id": ObjectId("564ab9847628ba2c81f2f34a")}}}).pretty()
I am unable to do the same using mgo and have tried the following:
Using nesting (Throws: missing type in composite literal, missing key in map literal)
// Using nesting (Throws: missing type in composite literal, missing key in map literal)
c.Find(bson.M{{"_id": bson.ObjectIdHex(p.ByName("id"))}, bson.M{"races": bson.M{"$elemMatch": bson.M{"_id": bson.ObjectIdHex(p.ByName("raceId"))}}}}).One(&result)
// Using select (Returns empty)
c.Find(bson.M{"_id": bson.ObjectIdHex(p.ByName("id"))}).Select(bson.M{"races._id": bson.ObjectIdHex(p.ByName("raceId"))}).One(&result)
//As an array (Returns empty)
c.Find([]bson.M{{"_id": bson.ObjectIdHex(p.ByName("id"))}, bson.M{"races": bson.M{"$elemMatch": bson.M{"_id": bson.ObjectIdHex(p.ByName("raceId"))}}}}).One(&result)
I am using httprouter and p.ByName("...") invocations are parameters passed to the handler.
Thanks in advance.
Would go with the Select method as the doc states that this enables selecting which fields should be retrieved for the results found, thus the projection using $elemMatch operator can be applied here in conjuction with Select, with your final query looking something like:
c.Find(bson.M{
"_id": bson.ObjectIdHex(p.ByName("id"))
}).Select(bson.M{
"races": bson.M{
"$elemMatch": bson.M{
"_id": bson.ObjectIdHex(p.ByName("raceId"))
}
}
}).One(&result)

Mongo query with 'like' (regex); extract the field that provide the matching

I'm looking some way for extract the field that provide matching. Example from mongo shell:
db.estates.find({$or: [{street: /a/i}, {number: '64'}]}, {street: 1, number: 1})
{ "_id" : ObjectId("551f8b1efec981df83afbaee"), "number" : "123", "street" : "abcd" }
{ "_id" : ObjectId("551f8b36fec981df83afbb05"), "street" : "qwer", "number" : "64" }
I want to get in results some value pointing to field that provided the matching, or get only this field. Is it real?

Array query and return

My first adventure into Mongo. Please save me some time by answering the following. This is the schema.
"_id" : 1,
"FullName" : "Full Name",
"Email" : "email#email.com",
"FacebookId" : NumberLong(0),
"LastModified" : ISODate("2012-04-11T09:26:10.955Z"),
"Connections" : [{
"_id" : 7,
"FullName" : "Fuller name",
"Email" : "connections#email.com",
"FacebookId" : NumberLong(0),
"LastModified" : ISODate("0001-01-01T00:00:00Z")
},
....
Given an id of a single top user, i'd like to return all of the Emails in the Connections array, and preferably, just the emails. What's the querystring? Much obliged!
You can't get only values from the sub-objects in MongoDB.
If you do a query like this:
db.test.find({"_id": 1}, {"Connections.Email":1});
you will get this kind of response:
{
"_id": 1,
"Connections" : [ {"Email":"connections#email.com"},
{"Email":"foo#example.com"} ]
}
This is the closest you can get with a simple query and field selection from MongoDB.
You can then filter out the e-mails values in your code with a simple foreach.