mongodb search on single key of document - mongodb

I have mongodb document with data as following :
[{
"name": "Robin singh",
"developer": "java",
"address": "Robin Singh,Mohali",
"search_string": ["Robin", "Singh", "java"]
}, {
"name": "Rohan singh",
"developer": "java",
"address": "Rohan Singh,Mohali",
"search_string": ["Rohan", "Singh", "java"]
}]
I want to search document with developer java with name Rohan singh and I used this query:
{"search_string":{"$all":["Robin","Singh","java"]}}
but I am getting both results.

If you have both name and developer then you can simply use find query -
db.collection.find({"name":"Rohan singh", "developer":"java"})
Additionally, If you want to check when search_string contains exact parameters which you are passing in $all then - You need to use combination of $size and $all operator to get desired result. size must be the number of parameters that you are using in $all. Here you must check size of search_string to number of params in $all so that it will search given parameters ($all) only in those search_string which size matches to number of params.
Following query might be helpful to you.
db.collection.find({
"name":"Rohan singh",
"search_string": {
$all: ["Rohan", "singh","java"]
},
"search_string": {
$size: 3 // This is the number of param you pass in $all
}
}).pretty()

Try:
db.testcollection.aggregate([
{ $match: {"search_string":{"$all":["Robin","Singh","java"]}} },
{ $group: { _id: "$name"} }
])

Related

Mongodb find documents with a specific aggregate value in an array

I have a mongo database with a collection of countries.
One property (currencies) contains an array of currencies.
A currency has multiple properties:
"currencies": [{
"code": "EUR",
"name": "Euro",
"symbol": "€"
}],
I wish to select all countries who use Euro's besides other currencies.
I'm using the following statement:
db.countries.find({currencies: { $in: [{code: "EUR"}]}})
Unfortunately I'm getting an empty result set.
When I use:
db.countries.find({"currencies.code": "EUR"})
I do get results. Why is the first query not working and the second one succesfull?
The first query is not working as it checks whether the whole currency array is in the array, which is never true.
It is true when:
currencies: {
$in: [
[{
"code": "EUR",
"name": "Euro",
"symbol": "€"
}],
...
]
}
I believe that $elemMatch is what you need besides the dot notation.
db.collection.find({
currencies: {
$elemMatch: {
code: "EUR"
}
}
})
Sample Mongo Playground
MongoDB works in the same way if the query field is an array or a single value, that's why the second one works.
So why the first one doesn't work? The problem here is that you are looking for an object that is exactly defined as {code: "EUR"}: no name or symbol field are specified. To make it work, you should change it to:
db.getCollection('countries').find({currencies: { $in: [{
"code" : "EUR",
"name" : "Euro",
"symbol" : "€"
}]}})
or query the subfield directly:
db.getCollection('stuff').find({"currencies.code": { $in: ["EUR"]}})

How to match two different Object ids using MongoDB find() query?

I have an entry like below,
[
{
"_id":ObjectId("59ce020caa87df4da0ee2c78"),
"name": "Tom",
"owner_id": ObjectId("59ce020caa87df4da0ee2c78")
},
{
"_id":ObjectId("59ce020caa87df4da0ee2c79"),
"name": "John",
"owner_id": ObjectId("59ce020caa87df4da0ee2c78")
}
]
now, I need to find the person whose _id is equal to owner_id using find() in MongoDB.
Note, we can't not use $match (aggregation) due to some reason.
I am using this query,
db.people.find({ $where: "this._id == this.owner_id" })
but, it's not returning the expected output. Can anyone help me with this.
Thanks.
Using $expr and $eq you can get desired values avoiding the use of $where into a find stage (not aggregation necessary).
db.collection.find({
"$expr": {
"$eq": [
"$_id",
"$owner_id"
]
}
})

Trying to fetch data from Nested MongoDB Database?

I am beginner in MongoDB and struck at a place I am trying to fetch data from nested array but is it taking so long time as data is around 50K data, also it is not much accurate data, below is schema structure please see once -
{
"_id": {
"$oid": "6001df3312ac8b33c9d26b86"
},
"City": "Los Angeles",
"State":"California",
"Details": [
{
"Name": "Shawn",
"age": "55",
"Gender": "Male",
"profession": " A science teacher with STEM",
"inDate": "2021-01-15 23:12:17",
"Cars": [
"BMW","Ford","Opel"
],
"language": "English"
},
{
"Name": "Nicole",
"age": "21",
"Gender": "Female",
"profession": "Law student",
"inDate": "2021-01-16 13:45:00",
"Cars": [
"Opel"
],
"language": "English"
}
],
"date": "2021-01-16"
}
Here I am trying to filter date with date and Details.Cars like
db.getCollection('news').find({"Details.Cars":"BMW","date":"2021-01-16"}
it is returning details of other persons too which do not have cars- BMW , Only trying to display details of person like - Shawn which have BMW or special array value and date too not - Nicole, rest should not appear but is it not happening.
Any help is appreciated. :)
A combination of $match on the top-level fields and $filter on the array elements will do what you seek.
db.foo.aggregate([
{$match: {"date":"2021-01-16"}}
,{$addFields: {"Details": {$filter: {
input: "$Details",
as: "zz",
cond: { $in: ['BMW','$$zz.Cars'] }
}}
}}
,{$match: {$expr: { $gt:[{$size:"$Details"},0] } }}
]);
Notes:
$unwind is overly expensive for what is needed here and it likely means "reassembling" the data shape later.
We use $addFields where the new field to add (Details) already exists. This effectively means "overwrite in place" and is a common idiom when filtering an array.
The second $match will eliminate docs where the date matches but not a single entry in Details.Cars is a BMW i.e. the array has been filtered down to zero length. Sometimes you want to know this info so if this is the case, do not add the final $match.
I recommend you look into using real dates i.e. ISODate instead of strings so that you can easily take advantage of MongoDB date math and date formatting functions.
Is a common mistake think that find({nested.array:value}) will return only the nested object but actually, this query return the whole object which has a nested object with desired value.
The query is returning the whole document where value BMW exists in the array Details.Cars. So, Nicole is returned too.
To solve this problem:
To get multiple elements that match the criteria you can do an aggregation stage using $unwind to separate the different objects into array and match by the criteria you want.
db.collection.aggregate([
{
"$match": { "Details.Cars": "BMW", "date": "2021-01-26" }
},
{
"$unwind": "$Details"
},
{
"$match": { "Details.Cars": "BMW" }
}
])
This query first match by the criteria to avoid $unwind over all collection.
Then $unwind to get every document and $match again to get only the documents you want.
Example here
To get only one element (for example, if you match by _id and its unique) you can use $elemMatch in this way:
db.collection.find({
"Details.Cars": "BMW",
"date": "2021-01-16"
},
{
"Details": {
"$elemMatch": {
"Cars": "BMW"
}
}
})
Example here
You can use $elemenMatch into query or projection stage. Docs here and here
Using $elemMatch into query the way is this:
db.collection.find({
"Details": {
"$elemMatch": {
"Cars": "BMW"
}
},
"date": "2021-01-16"
},
{
"Details.$": 1
})
Example here
The result is the same. In the second case you are using positional operator to return, as docs says:
The first element that matches the query condition on the array.
That is, the first element where "Cars": "BMW".
You can choose the way you want.

Querying array and ignoring the order of the elements

Consider a report that contains:
{
"name": "n1",
"version": "1.0",
"ids": ["ABC", "XYZ"]
}
I want to find all reports that contain that name, version and ids. So I built:
.find({ "name": "n1", "version": "1.0", "ids": ["ABC", "XYZ"]})
But the problem is that I don't know the order of the elements in the ids array. So the following query won't return reports:
.find({ "name": "n1", "version": "1.0", "ids": ["XYZ","ABC"]})
How can I tell the query to match if the array contains exactly does elements? Using MongoDB 3.2 and Pymongo.
You need to combine $size with $all, like so:
The $all operator selects the documents where the value of a field is
an array that contains all the specified elements
The $size operator matches any array with the number of elements
specified by the argument
{
"cast": {
$all: ['Peter Courtney', 'James J. Corbett'],
$size : 2
}
}
But be careful because it can be a very expensive operation.
You can use $all and $and operators, not the best and would need to determine size of array upfront
.find( { "name": "n1", "version": "1.0" , "ids" : { $all: ["XYZ","ABC"] }, "ids": { $size: 2 }})
I think this should work on 3.2.

search in mongodb embedded records

We have a mongodb document as given below, and we configured text index on messageTopic, messageTopicQuestion and answer fields, if i search with a text string then I expect only matched embedded records in the results not the entire document.
For example in below document if i search with word "private", then results should only return the first embedded document not both the records. How to retrieve only matched embedded documents and exclude unmatched ones.
{
"_id": ObjectId("586e8efdde81e56032000084"),
"messageTopic": "My Private",
"messageText": [{
"messageTopicQuestion": "agent private",
"answer": "agent private",
"_id": ObjectId("586e8efdde81e56032000085"),
"keywords": ["private"]
}, {
"messageTopicQuestion": "Greetings Checking",
"answer": "Heloo I am good What about u",
"_id": ObjectId("586fc80ccced739407000f4e"),
"keywords": ["Hi-Good", "Heloo"]
}],
"__v": 3
}
I am using below script
db.getCollection('messagetemplates').aggregate([{
$match: {
$text: {$search: 'private'},
visible: 'PUB'
}
},{ $sort: { score: { $meta: "textScore" } } }])
Appreciate help. Thanks.
I believe the question is a variation of this problem How to get a specific embedded document inside a MongoDB collection?
The issue is how to get the single embedded document and exclude the rest. My suggestion is to use db.collection.find() instead of aggregation.
Something in that sense
db.collection.find({ 'messageText.keyword': 'private' }, {'messageText.$': 1});
, as indicated by the answer above.
messageText.keyword can be replaced with whichever field you want to be searched.
I can confirm that the scenario works on my database.