I have following data.
{
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : [
{
"data" : "twitter.com",
"privacy" : false
}
],
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
I want to return only data having privacy is equal to true. How do I do it ?
I tried but it returns all data having privacy is equal to false also. How do I query the data ?
Please post MongoDB query not Javascript code.
Thanks!
edit
having structure like this:
{
"_id" : ObjectId("575e4c8731dcfb59af388e1d"),
"name" : "Maria",
"providers" : [
{
"type" : "facebook",
"data" : "fb.com",
"privacy" : true
},
{
"type" : "twitter",
"data" : "twitter.com",
"privacy" : false
},
{
"type" : "google",
"data" : "google.com",
"privacy" : true
},
{
"type" : "phno",
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
with query like this:
db.maria.aggregate([{
$project : {
_id : 1,
name : 1,
"providers" : {
$filter : {
input : "$providers",
as : "p",
cond : {
$eq : ["$$p.privacy", true]
}
}
}
}
}
])
])
we are gaining dynamic output, and we don't need to take care about provider name as this is covered by generic structure
{
"providers" : [
{
"type" : "facebook",
"data" : "fb.com",
"privacy" : true
},
{
"type" : "google",
"data" : "google.com",
"privacy" : true
},
{
"type" : "phno",
"data" : "+1-1289741824124",
"privacy" : true
}
],
"name" : "Maria"
}
end of edit
The way you could get this is using aggregation framework.
As we have an array for each field, we need to unwind it first, then we can use $project to set field value or simply null. As this looks like a simple query, it could give a bit of trouble. The way we can improve that is change a document structure, to have an array of providers and simple providerType field.
Aggregation stages below:
db.maria.find()
var unwindFb = {
$unwind : "$facebook"
}
var unwindtw = {
$unwind : "$twitter"
}
var unwindgo = {
$unwind : "$google"
}
var unwindph = {
$unwind : "$phno"
}
var project = {
$project : {
_id : 1,
name : 1, // list other fields here
facebook : {
$cond : {
if : {
$gte : ["$facebook.privacy", true]
},
then : [{
data : "$facebook.data",
privacy : "$facebook.privacy"
}
],
else : null
}
},
twitter : {
$cond : {
if : {
$gte : ["$twitter.privacy", true]
},
then : [{
data : "$twitter.data",
privacy : "$twitter.privacy"
}
],
else : null
}
},
google : {
$cond : {
if : {
$gte : ["$google.privacy", true]
},
then : [{
data : "$google.data",
privacy : "$google.privacy"
}
],
else : null
}
},
phno : {
$cond : {
if : {
$gte : ["$phno.privacy", true]
},
then : [{
data : "$phno.data",
privacy : "$phno.privacy"
}
],
else : null
}
}
}
}
db.maria.aggregate([unwindFb, unwindtw, unwindgo, unwindph, project])
then output looks like this:
{
"_id" : ObjectId("575df49d31dcfb59af388e1a"),
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : null,
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
you can use the below code to iterate the object and check for the privacy true
var list = {
"name" : "Maria",
"facebook" : [
{
"data" : "fb.com",
"privacy" : true
}
],
"twitter" : [
{
"data" : "twitter.com",
"privacy" : false
}
],
"google" : [
{
"data" : "google.com",
"privacy" : true
}
],
"phno" : [
{
"data" : "+1-1289741824124",
"privacy" : true
}
]
}
$.each(Object.keys(list), function(index,value){
if(list[value][0].privacy)
{
console.log(list[value][0]);
}
});
If you are open to use lodash ...this is how you can do it...
var tmp = {
...you json here
}
var res =[];//result array of filtered data
_.forIn(tmp, function (o) {
if (Array.isArray(o)) {
if (o[0].privacy === true) {
res.push(o);
}
}
});
Related
Below is my JSON structure
[{
"_id" : ObjectId("626204345ae3d8ec53ef41ee"),
"categoryName" : "Test Cate",
"__v" : 0,
"createdAt" : ISODate("2022-04-22T01:26:11.627Z"),
"items" : [
{
"itemName" : "Cate",
"user" : ObjectId("6260729af547915d9d876c23"),
"itemDescription" : "slkkndanslk",
"itemImage" : "/images/camping-table.jpeg",
"_id" : ObjectId("626204339b24b2ead6c05a70"),
"updatedAt" : ISODate("2022-04-22T01:26:11.627Z"),
"createdAt" : ISODate("2022-04-22T01:26:11.627Z")
}
],
"updatedAt" : ISODate("2022-04-22T01:26:11.627Z")
},
{
"_id" : ObjectId("62620e725ae3d8ec53ef4aa8"),
"categoryName" : "sdsad",
"__v" : 0,
"createdAt" : ISODate("2022-04-22T02:09:54.028Z"),
"items" : [
{
"itemName" : "asdada",
"user" : ObjectId("62620e6299145edb95147482"),
"itemDescription" : "asdsadad",
"itemImage" : "/images/camping-table.jpeg",
"_id" : ObjectId("62620e7299145edb95147486"),
"updatedAt" : ISODate("2022-04-22T02:09:54.028Z"),
"createdAt" : ISODate("2022-04-22T02:09:54.028Z")
},
{
"itemName" : "dsdsa",
"user" : ObjectId("62620e6299145edb95147482"),
"itemDescription" : "adasdad",
"itemImage" : "/images/camping-table.jpeg",
"_id" : ObjectId("62621b9c3662e0b4acabb71f"),
"updatedAt" : ISODate("2022-04-22T03:06:04.727Z"),
"createdAt" : ISODate("2022-04-22T03:06:04.727Z")
}
],
"updatedAt" : ISODate("2022-04-22T03:06:04.727Z")
}]
This is just one document and there would be array of documents. Also there may be multiple items within the same category.
I want to fetch all the items in all category with a particular userid. In MongoDB below is my query which is giving correct output on mongo shell
db.trades.aggregate([
{
$unwind: "$items"
},
{
$match: {
"items.user": ObjectId("6260729af547915d9d876c23")
}
}
]).pretty()
In mongoose I am doing the following thing but not getting the result
tradeModel.aggregate([ { $unwind : "$items" }, { $match : { "items.user" : id } } ])
.then(res => {
console.log(JSON.stringify(res))
})
Let me know what I am missing
Your parameter id is type string but mongodb store type ObjectId
change
tradeModel.aggregate([ { $unwind : "$items" }, { $match : { "items.user" : id } } ])
.then(res => {
console.log(JSON.stringify(res))
})
into
tradeModel.aggregate([ { $unwind : "$items" }, { $match : { "items.user" : {"$oid": id} } } ])
.then(res => {
console.log(JSON.stringify(res))
})
Got the answer we can use ObjectId(id) in search like this
tradeModel.aggregate([ { $unwind : "$items" }, { $match : { "items.user" : ObjectId(id) } } ])
.then(res => {
console.log(JSON.stringify(res))
})
I have a Firebase realtime-database export-json that has nested informations, that I would like to extract. The structure of the JSON looks like this:
{
"users" : {
"024w97mv8NftGFY8THfQIU6PhaJ3" : {
"email" : "xxx",
"id" : "024w97mv8NftGFY8THfQIU6PhaJ3",
"name" : "xxx",
"items" : {
"-LQL9n-r9BGdo3HJZ2sk" : {
"disliked" : true,
"id" : 396,
"name" : "Aaa"
},
"-LQL9oO63nH-QW2w6zz0" : {
"liked" : true,
"id" : 3674,
"name" : "Bbb"
}
}
},
"0ERLT5DLRvbZUnjlnM7Ow0qItpz2" : {
"email" : "zzz",
"id" : "0ERLT5DLRvbZUnjlnM7Ow0qItpz2",
"name" : "zzz",
"items" : {
"-LIZnriSVQMzqTsPFNYa" : {
"id" : 396,
"liked" : true,
"name" : "Aaa"
},
"-LIZnrzOuk4WyjqEiLG8" : {
"disliked" : true,
"id" : 4805,
"name" : "Ccc"
}
}
}
}
}
What I need to achieve is getting a list of all liked item-names, and ideally counting how often an item is liked.
Is there a simple tool or script to do that? Ruby or Javascript would be preferred. Thanks a lot!
You can parse your JSON data in ruby like below
result_hash = JSON.parse(result)
result_ary = result_hash["users"].collect do |k,v|
v["items"].values.select{|v1| v1["liked"] == true }
end
result_data = result_ary.flatten
result of parsing
=> [{"liked"=>true, "id"=>3674, "name"=>"Bbb"}, {"id"=>396, "liked"=>true, "name"=>"Aaa"}]
Now its very easy for getting your required result
result_data.collect{|x| x["name"] }
=> ["Bbb", "Aaa"]
result_data.count {|x| x["name"] == "Aaa"}
=> 1
result_data.count {|x| x["name"] == "Bbb"}
=> 1
i`m trying to delete a element inside a field of my elastic field, current, I have this struct of data:
I need in my NODE application to delete a single element from produto_tags getting the id_produto_cor,
for example:
{
"_index" : "relatorio_recebimento_produto_hml",
"_type" : "_doc",
"_id" : "54XZ9HAB4DHa2O1nQlpk",
"_score" : 1.0,
"_source" : {
"id_usuario" : 1408,
"data_criacao" : "2020-03-19T22:10:40.465Z",
"produto_tags" : [
{
"id_produto_cor" : "2489664268",
"tags" : [ ]
},
{
"id_produto_cor" : "1000045010",
"tags" : [ ]
},
{
"id_produto_cor" : "1004600287",
"tags" : [ ]
},
{
"id_produto_cor" : "1032013410",
"tags" : [ ]
},
{
"id_produto_cor" : "2468436987",
"tags" : [ ]
}
],
"referencia_tags" : [ ],
"nome_relatorio" : "teste"
}
}
XDELETE
{
query: {
match: {
produto_tags.id_produto_cor: 489664268
}
}
}
I would expect my data to be like:
"_index" : "relatorio_recebimento_produto_hml",
"_type" : "_doc",
"_id" : "xYVD5XAB4DHa2O1ndFo1",
"_score" : 1.0,
"_source" : {
"id_usuario" : 1376,
"data_criacao" : "2020-03-16T21:32:46.369Z",
"produto_tags" : [
{
"id_produto_cor" : "1000045010",
"tags" : [ ]
},
{
"id_produto_cor" : "1004600287",
"tags" : [ ]
},
{
"id_produto_cor" : "1032013410",
"tags" : [ ]
},
{
"id_produto_cor" : "2468436987",
"tags" : [ ]
}
],
"referencia_tags" : { },
"nome_relatorio" : "teste"
}
},
...
This is my final structure
zzzzzzzzzzzzzzzzzzzz
zzzzzzzzzzzzzzzzzzzz
You can use _update_by_query
POST /index102/_update_by_query
{
"script":{
"source":"ctx._source.produto_tags.remove('1029831004')"
},
"query":{
"match_all":{} --> modify query to target specific documents
--> match_all will execute script on all documents
}
}
Query for changed structure:
iterate through produto_tags, match with specific value and store the matched object in an array (list). Then iteratate through list and remove the object from produto_tags
POST /<index_name>/_update_by_query
{
"script":{
"source":"if(ctx._source.produto_tags.size()==0) {return;} def list=[]; for(product in ctx._source.produto_tags) { if (product['id_produto_cor'] ==params.product_id){list.add(product)}} if(list.size()==0) return; for(d in list){ctx._source.produto_tags.remove(ctx._source.produto_tags.indexOf(d))}",
"params" : {
"product_id" : "2468436987"
}
},
"query":{
"match_all":{} --> to select specific documents
}
}
I want this to be the result
help me, thank you
{
"_id" : ObjectId("5b74f57d3eb9591fcc069406"),
"received_by" : ObjectId("5b6bac617e9f754ff8aebd65"),
"received_date" : "2019",
"code" : "TRSV16081800007",
"items" : [
{
"m_souvenir_id" : ObjectId("5b70e98ccb72df3bec00c94a"),
"qty" : "10"
},
{
"m_souvenir_id" : ObjectId("5b70e98ccb72df3bec00c94a"),
"qty" : "10"
},
]
}
the result is like this
{
"_id" : ObjectId("5b74f57d3eb9591fcc069406"),
"received_by" : ObjectId("5b6bac617e9f754ff8aebd65"),
"received_date" : "2019",
"code" : "TRSV16081800007",
"items" : [
{
"m_souvenir_id" : ObjectId("5b70e98ccb72df3bec00c94a"),
"qty" : "10"
}
]
}
/* 2 */
{
"_id" : ObjectId("5b74f57d3eb9591fcc069406"),
"received_by" : ObjectId("5b6bac617e9f754ff8aebd65"),
"received_date" : "2019",
"code" : "TRSV16081800007",
"items" : [
{
"m_souvenir_id" : ObjectId("5b70e9d7cb72df3bec00c94b"),
"qty" : "20"
}
]
}
I have a project with nosql in mongodb
I have a problem with nosql in mongodb, I've tried searching in various sources, but the results are still not what I wantI have a project like this in mongodb,
db.t_souvenir.aggregate([
{ $lookup: { from: "t_souvenir_item", localField:"_id", foreignField:"t_souvenir_id", as: "Items"}},
{ $unwind : "$Items" },
{ $project : {
"code":1,
"received_by":1,
"received_date":1,
items : {
"m_souvenir_id":"$Items.m_souvenir_id",
"qty":"$Items.qty",
},
}};**strong text**
]);
I have mongoDB "users" collection in JSON format and I want to return all the data having privacy is true. How can I do it ?
{
"name" : "Maria Kari",
"social" : [
{
"facebook" : "www.fb.com/maria.mongodb",
"privacy" : true
},
{
"twitter" : "www.tw.com/mongodb",
"privacy" : false
}
],
"personal" : [
{
"cell_no" : "+1-99082198414",
"privacy" : true
},
{
"email" : "maria#mongodb.com",
"privacy" : false
}
]
}
Here, I want to return the data having privacy is true. For example, facebook, it has privacy is equal to true. How to build query for this ?
Thank You. :')
db.users.find( {
$or:[{ 'social.privacy': true },{'personal.privacy': true}]
)