I am looking for a Mongo query for finding data in the following document.
{
"key1": [{
"subkey1": ["america.south.gas"],
"subkey2": ["9898989898"]
}],
"key2": [{
"subkey1": ["america"],
"subkey2": ["hsadjsahjsahdjsah879878u9"]
},
{
"subkey1": ["america.south.gas","america"],
"subkey2": ["hsadjsahjsahdjsah879878u9"]
},
{
"subkey1": ["america.south.#"],
"subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]
}]
}
I want only subkey2 only of above mentioned document as following output:
"subkey2": ["hsadjsahjsahdjsah879878u9"]
"subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]
Now I want to fetch data with following query:-
db.collectionName.find({$or:[
{"key2.subkey1": "america.south.gas"},
{"key1.subkey1": "america.south.#"}
]},
{"_id": 0, "key2.subkey2.$": 1}
);
But it is showing me this error:
{
"waitedMS" : NumberLong(0),
"ok" : 0,
"errmsg" : "Executor error during find command: BadValue: positional operator (key1.$) requires corresponding field in query specifier",
"code" : 96
}
Any idea how can I achieve this for getting specific field with multiple query field in Mongo find operation??
This error ...
Error: error: { "waitedMS" : NumberLong(0), "ok" : 0, "errmsg" : "Executor error during find command: BadValue: positional operator (key1.$) requires corresponding field in query specifier", "code" : 96 }
.. is caused by this projection:
"key2.subkey2.$": 1
Soecifically, the positional operator: $.
According to the comments above, you ...
want only subkey2 only of above mentioned document as following output:- "subkey2": ["hsadjsahjsahdjsah879878u9"] "subkey2": ["sjadkjsahdkjsahdj989s89d8sa98d9sa"]
The following command ...
db.collection.aggregate([
{$unwind:'$key2'},
// find the documents having key2.subkey1 = 'america.south.#' or key2.subkey1 = 'america.south.gas'
{$match:{'key2.subkey1':{$in:['america.south.#','america.south.gas']}}},
// limit the output to only those key2.subkey2 entries for which the associated key2.subkey1 match the previous $match clause
{$group:{_id:0,'subkey2':{$push:'$key2.subkey2'}}},
// only return subkey2
{$project: {_id: 0, 'subkey2':1}}
])
... will return:
{
"subkey2" : [
[
"hsadjsahjsahdjsah879878u9"
],
[
"sjadkjsahdkjsahdj989s89d8sa98d9sa"
]
]
}
#glytching, If i need output like that as below given then what need to change in query and also no duplicate output value.
{
"subkey2" : [ "hsadjsahjsahdjsah879878u9","sjadkjsahdkjsahdj989s89d8sa98d9sa"]
}
Related
{
"sections": [
{
"desc": "no flow ID",
"sectionObj": [
{
"smartFlowIdList": []
}
]
},
{
"desc": "has flow ID",
"sectionObj": [
{
"smartFlowIdList": [
"smartFlowId1",
"smartFlowId2"
]
}
]
]
}
// Query document to see if any of the sections[].sectionObj[].smartFlowIdList has at least a flowId1
// in this case: it is True since [ "smartFlowId1", "smartFlowId2" ] exits
I need to query this document with MongoDB shell commands.
I have tried looking at $[], $all and digging up on mongo documentation but can seem to get anywhere. Any idea is appreciated, thanks!
One option is to iterate twice, per each nested level and count the items in last nested level. $match documents with count greater than 0:
db.collection.aggregate([
{$match: {$expr:
{$gt: [
{$sum: {$map: {
input: "$sections",
as: "external",
in: {$sum: [
{$reduce: {
input: "$$external.sectionObj",
initialValue: 0,
in: {$sum: ["$$value", {$size: "$$this.smartFlowIdList"}]}
}
}
]
}
}}},
0
]}
}}
])
See how it works on the playground example
I have the following document in :
"Demo" : {
"SI" : {
"Value1" : 40,
"Value2" : [
10,
15,
20
]
} ,
"RS" : {
"Value1" : 4,
"Value2" : [
1,
2,
3,
4
]
}
}
I want to fetch the data for sub-document 'SI'. I have tried with following query:
db.getCollection('input').find({"Demo.SI":"SI"}), but its not giving any record for 'SI' document. The desired output is:
"SI" : {
"Value1" : 40,
"Value2" : [
10,
15,
20
]
}
Please specify where the query goes wrong.
First checkSI exists or not using $exists and then add it in projection as below :
db.input.find({"Demo.SI":{"$exists":true}},{"Demo.SI":1,"_id":0}).pretty()
db.collection.find({ "Demo.SI": { $exists: true, $ne: null } },{"Demo.SI":1,"_id":0})
This query will return all the documents which has SI key
This is JSON that I want to use for a search:
{
"_index" : "test", "_type" : "insert", "_id" : "3",
"_version" : 2, "found" : true,
"_source" : {
"ACCOUNT_ID" : "123",
"CONTACT_ID" : "ABC"
}
}
How do I search for all the JSON which have ACCOUNT_ID starting from 1?
You can use Wildcard in elasticsearch to search for an ACCOUNT_ID which starts from 1
GET index/_search
{
"query": {
"wildcard": {
"ACCOUNT_ID ": {
"value": "1*"
}
}
}
}
In Java, you can try something like this:
QueryBuilders.wildcardQuery("ACCOUNT_ID ", "1*");
From what i see in your comments you are trying to find id's starting with 1 for example. Well if your analyzer is the standard one the id "123" is tokenized like "123". You can use wildcard and search like '1*'. Be careful using wildcards cause it takes some memory.
See here: QueryString - Wildcard
This is my dbcollection in mongodb
{
"_id" : 0,
"name" : "+Anima",
"author" : "MUKAI Natsumi",
"type" : [
"Adventure",
"Fantasy"
],
"chapters" : [
{
"chapterName" : "+Anima 56",
"chapterLink" : "http://...",
"groupTranslate" : "Manga Palace Group",
"dateUpload" : 1359478800000,
"chapterNumber" : 56.0000000000000000,
"images" : [
"img0",
"img1",
"img2",
"img3"
]
},
{
"chapterName" : "+Anima 55",
"chapterLink" : "http://....",
"groupTranslate" : "Manga Palace Group",
"dateUpload" : 1410109200000,
"chapterNumber" : 55.0000000000000000,
"images" : [
"img0",
"img1",
"img2",
"img3"
]
}
]
}
I cannot find list chapter sort by "dateUpload" in mongodb using java code. Please help.
Mongo $aggregation will solve your problem. Below query first $unwind your chapters array and then sort dateUpload
db.collectionName.aggregate({
"$unwind": "$chapters" // unwind breaks the chapters array
}, {
"$sort": {
"chapters.dateUpload": -1 // then seperated chapters array sorted by dateUpload
}
}, {
"$group": {
"_id": "$_id",
"chapters": {
"$push": "$chapters" // group used for grouping chapters array
}
}
}).pretty()
And for converting above query in java code formatt then follow below mongo aggregation java driver code .
Java Driver and Aggregation Framework
This should do it, using aggregate():
db.foo.aggregate( [ { $project: {chapters: 1} },
{ $unwind: "$chapters" },
{ $sort: {"chapters.dateUpload": -1} }
] );
Extract the chapters subdocument with $project, then $unwind it to deconstruct the array and get each element, finally $sort them on dateUpload value (descending, use 1 for ascending order).
In my mongodb data base i'm having the data like below format
"_id": ObjectId("52b2802cd29e32f494463847"),
"Name": "Hai2",
"List": {
"0": "72",
"1": "46",
"2": "94",
"3": "13",
"4": {
"0": ObjectId("52b2801fd29e32f49446383c"),
"1": ObjectId("52b28020d29e32f49446383f"),
"2": ObjectId("52b28021d29e32f494463842")
}
etc ..(Like this many data is there in db save arrangement )
Now what i'm trying is, i want to retrieve the ObjectId list when the user inputs matches the `"0"` and `"1"` position of List key value.If i use `$in` it looks all the values of list.So i'm trying with `$slice` to slice the list and search to particular location.
Query i'm trying is,$slice -> { "$slice" : [ 0 , 2]}
$in -> { "$in" : [ "72" , "46"]}
If i try and for these two things, $and -> { "List" : { "$and" : [ { "$slice" : [ 0 , 2]} , { "$in" : [ "72" , "46"]}]}}
I'm getting exception,
com.mongodb.MongoException: invalid operator: $and
at com.mongodb.MongoException.parse(MongoException.java:82)
at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:314)
After i tried like,
searchQuery -> { "List" : { "$in" : [ "72" , "46"]}},
sliceQuery -> { "List" : { "$slice" : [ 0 , 2]}} ,
DBCursor dbCursor = collection.find(searchQuery, sliceQuery)
For this i'm getting the result like searching in all the fields and slicing the list result field
Can any one suggest me how to $slice first after that apply $in for the sliced result ??(i'm using mongo-java-driver2.10.1)
Thanks
I'm guessing it's that first $and that's not in quotes. But since I can't see your actual java code I can only guess at this point.