mongo c-driver bcon $ne value no equal - mongodb

I am trying to append a requirement to my BCON query where 'tribe_type' does not equal 'initial-public'.
My original code was and that worked:
query = BCON_NEW ("_id", BCON_OID(&oid));
When I add the second part, it compiles, however the mongo match fails.
query = BCON_NEW ("_id", BCON_OID(&oid),
"{",
"tribe_type",
"$ne",
"initial-public",
"}"
);

You have to specify the BCON type for UTF-8 strings.
Be careful with implict $and's
Be careful with nested documents and BCON.
query = BCON_NEW ("_id", BCON_OID(&oid),
"{",
"tribe_type",
"$ne",
"initial-public",
"}"
);
compiles into this command
{ "_id" : <an oid> }, { "tribe_type" : "$ne" }
which is obviously not what you want.
be explicit with the $and operation, correctly type the string as a UTF8 field, and make sure you capture the nested documents like this:
query = BCON_NEW (
"$and", "[", "{", "_id", BCON_OID(&oid), "}",
"{", "tribe_type", "{", "$ne", BCON_UTF8 ("initial-public"), "}", "}","]"
);
yields a query that looks like this
{ "$and" : [ { "_id" : <an oid> }, { "tribe_type" : { "$ne" : "initial-public" } } ] }
which is probably what you want.

query = BCON_NEW ("_id", BCON_OID(&oid),
"tribe_type",
"{",
"$ne", BCON_UTF8 ("initial-public"),
"}");

Related

How to query in Monogdb when JSON contain \ and not in proper format?

This is a MongoDB document in which I try to get "ID" and "Node 2", but I can't get values ​​from it.
{
"_id" : ObjectId("5deb99b8cfee8a21b0bd7500"),
"topic" : "outTopic",
"value" : "{ \"Reading No\": \" 3885 \",\"ID\":\" 946\", \"node 2\": \"20.00 *C\"} ",
"time" : ISODate("2019-12-07T17:53:20.744Z")
}
below queries, I tried.
db.collection.find({"topic":"outTopic","value.ID":"884"}).count(); #output 0
0r
db.collection.find({"topic":"outTopic","value":{"ID":"884"}}).count(); #output 0
Use the $regex operator to find a substring:
db.collection.find({
"topic": "outTopic",
"value": {
$regex: "\"ID\":\"9463440403\""
}
})
Hope that helps!

reserved words (Where, from , and) in full text search query in mongo db

I am using mongodb, I am stucked on a issue :
Data is :
{
"_id" : ObjectId("5a956e0b78d363d37f6a2ec4"),
"fieldType" : "Enter Source",
"value" : "Delhi",
"catgeory" : "Generic",
"synonym" : [
"origin name or code",
"from",
"enter source",
"from where",
"fro wher"
]
}
When I use this query
db.getCollection("Rules_DefaultValue").find(
{
"synonym" : "from where"
});
I got correct result as expected
But when I use this query
db.getCollection("Rules_DefaultValue").find(
{
"$text" : {
"$search" : "where"
}
});
I didn't got any result , So I changed it again
db.getCollection("Rules_DefaultValue").find(
{
"$text" : {
"$search" : "wher"
}
});
and this time it worked.
So I came to a conclusion that "where" is reserve keyword and I can't use it as it is. So I tried with escape char :
"$search" : "\"where\""
but again I did'nt got the result.
same thing is happening with
and , from , *
Please help me on this , How can I make query with these words.
Words like where and from are considered as stopwords in MongoDB. It means that when you create a text index those words are wiped out from the index since they appear very frequently in English while the point of FTS is to index some words that allow you to easily find the document you're looking for. To fix that you can create your text index specifying language to none, try:
db.getCollection("Rules_DefaultValue").createIndex(
{ synonym : "text" },
{ default_language: "none" }
)
Then your query should return the document mentioned in your post.

Nested Array Search in Mongo db using regex

what would be query for searching in nested arrays:
"_id" : "123",
"Array1" : [
{
"field1" : {
"nestedArray1" : [
{
"content" : "This string inside %nestedArray%",
}
]
},
}
],
I have tried using the following regex
Array1.field1.nestedArray1.content
Document doc = new Document();
doc.append("Array1.field1.nestedArray1.content", new Document("$regex", ".*" + "%nestedArray%" + ".*"));
But i am not able to get the proper results..Is the above query in right format

Distinct/Aggregation query Mongodb array, trim trailing space

I have a MongoDB collection which contains a colours array like :
myCollection :
{
_id : ...,
"colours" : [
{
"colourpercentage" : "42",
"colourname" : "Blue"
},
{
"colourpercentage" : "32",
"colourname" : "Red"
},
{
"colourpercentage" : "10",
"colourname" : "Green "
}
]
}
I would like to retrieve every distinct colourname of every entry of this collection, and be able to filter it with a search.
I tried with distinct but without success. I searched further and found that an aggregation could help me. For the moment I have :
db.getCollection('myCollection').aggregate([
{ "$match": { "colours.colourname": /Gre/ } }, # Gre is my search
{ "$unwind": "$colours" },
{ "$match": { "colours.colourname": /search/ } },
{ "$group": {
"_id": "$colours.colourname"
}}
])
It is working, but I get an array like :
{
"result" : [
{
"_id" : "Grey"
},
{
"_id" : "Light Green "
},
{
"_id" : "Light Green"
},
{
"_id" : "Green "
},
{
"_id" : "Green"
}
],
"ok" : 1.0000000000000000
}
And I would like to remove duplicate entries which have a space in the end and displays them like :
["Grey","Light Green","Green"]
One approach you could take is the Map-Reduce way even though the JavaScript interpreter driven mapReduce takes a bit longer than the aggregation framework but will work since you will be using some very useful native JavaScript functions that are lacking in the aggregation framework. For instance, in the map function you could use the trim() function to remove any trailing spaces in your colourname fields so that you can emit the "cleansed" keys.
The Map-Reduce operation would typically have the following map and reduce functions:
var map = function() {
if (!this.colours) return;
this.colours.forEach(function (c){
emit(c.colourname.trim(), 1)
});
};
var reduce = function(key, values) {
var count = 0;
for (index in values) {
count += values[index];
}
return count;
};
db.runCommand( { mapreduce : "myCollection", map : map , reduce : reduce , out : "map_reduce_result" } );
You can then query map_reduce_result collection with the regex to have the result:
var getDistinctKeys = function (doc) { return doc._id };
var result = db.map_reduce_result.find({ "_id": /Gre/ }).map(getDistinctKeys);
print(result); // prints ["Green", "Grey", "Light Green"]
-- UPDATE --
To implement this in Python, PyMongo's API supports all of the features of MongoDB’s map/reduce engine thus you could try the following:
import pymongo
import re
from bson.code import Code
client = pymongo.MongoClient("localhost", 27017)
db = client.test
map = Code("function () {"
" if (!this.colours) return;"
" this.colours.forEach(function (c){"
" emit(c.colourname.trim(), 1)"
" });"
"};")
reduce = Code("function (key, values) {"
" var count = 0;"
" for (index in values) {"
" count += values[index];"
" }"
" return count;"
" };")
result = db.myCollection.map_reduce(map, reduce, "map_reduce_result")
regx = re.compile("Gre", re.IGNORECASE)
for doc in result.find({"_id": regx}):
print(doc)

MongoDB bulk insert failing for array of strings

Given the following array:
arr = ["{'myId': 'myVal1'}","{'myId': 'myVal2'}"]
I can insert the items one by one, e.g.
db.collection.insert(arr[0])
But it fails when I try to insert the whole array (like it says in http://docs.mongodb.org/manual/reference/method/db.collection.insert/ )
db.collection.insert(arr)
Error: not an object src/mongo/shell/collection.js:179
I'm using MongoDB 2.2.4
How can I make this work?
You are trying to insert an array of strings - mongo expects an array of json documents.
"{'foo':'bar'}" is a string.
{'foo':'bar'} is an object - a json document with one key value pair.
It looks to you like the insert is succeeding when you do
db.collection.insert("{'foo':'bar'}") but it's not doing what you think it is.
> db.collection.findOne()
{
"_id" : ObjectId("51941c94c12b0a7bbd416430"),
"0" : "{",
"1" : "'",
"2" : "f",
"3" : "o",
"4" : "o",
"5" : "'",
"6" : ":",
"7" : "'",
"8" : "b",
"9" : "a",
"10" : "r",
"11" : "'",
"12" : "}",
"trim" : function __cf__12__f__anonymous_function() {
return this.replace(/^\s+|\s+$/g, "");
},
"ltrim" : function __cf__13__f__anonymous_function() {
return this.replace(/^\s+/, "");
},
"rtrim" : function __cf__14__f__anonymous_function() {
return this.replace(/\s+$/, "");
},
"startsWith" : function __cf__15__f__anonymous_function(str) {
return this.indexOf(str) == 0;
},
"endsWith" : function __cf__16__f__anonymous_function(str) {
return (new RegExp(RegExp.escape(str) + "$")).test(this);
}
}
I already put a pointer to this question/answer in your other question which asks how to convert this string.