Mongo $lookup Query Getting as alias blank - java

db.ticket.aggregate([
{
$lookup: {
from: "crmorder",
localField: "subOrderId",
foreignField: "currentStatus",
as: "comments"
}
}
])
in the result comments field is getting blank why?

you have one more table in name of crmorder
In ticket table must have - subOrderId field
In crmorder table must have - currentStatus field
and also ticket table subOrderId field == crmorder table currentStatus field
here is the sample snippt:
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
{ "_id" : 3 }
])
db.inventory.insert([
{ "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
{ "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
{ "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
{ "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
{ "_id" : 5, "sku": null, description: "Incomplete" },
{ "_id" : 6 }
])
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])

Related

How to write a MongoDB lookup query between 2 collections using Java?

For example, create an example collection classes with the following document:
db.classes.insert( [
{ _id: 1, title: "Reading is ...", enrollmentlist: [ "giraffe2", "pandabear", "artie" ], days: ["M", "W", "F"] },
{ _id: 2, title: "But Writing ...", enrollmentlist: [ "giraffe1", "artie" ], days: ["T", "F"] }
])
Create another collection members with the following documents:
db.members.insert( [
{ _id: 1, name: "artie", joined: new Date("2016-05-01"), status: "A" },
{ _id: 2, name: "giraffe", joined: new Date("2017-05-01"), status: "D" },
{ _id: 3, name: "giraffe1", joined: new Date("2017-10-01"), status: "A" },
{ _id: 4, name: "panda", joined: new Date("2018-10-11"), status: "A" },
{ _id: 5, name: "pandabear", joined: new Date("2018-12-01"), status: "A" },
{ _id: 6, name: "giraffe2", joined: new Date("2018-12-01"), status: "D" }
])
The following aggregation operation joins documents in the classes collection with the members collection, matching on the members field to the name field:
db.classes.aggregate([
{
$lookup:
{
from: "members",
localField: "enrollmentlist",
foreignField: "name",
as: "enrollee_info"
}
}
])
The operation returns the following:
{
"_id" : 1,
"title" : "Reading is ...",
"enrollmentlist" : [ "giraffe2", "pandabear", "artie" ],
"days" : [ "M", "W", "F" ],
"enrollee_info" : [
{ "_id" : 1, "name" : "artie", "joined" : ISODate("2016-05-01T00:00:00Z"), "status" : "A" },
{ "_id" : 5, "name" : "pandabear", "joined" : ISODate("2018-12-01T00:00:00Z"), "status" : "A" },
{ "_id" : 6, "name" : "giraffe2", "joined" : ISODate("2018-12-01T00:00:00Z"), "status" : "D" }
]
}
{
"_id" : 2,
"title" : "But Writing ...",
"enrollmentlist" : [ "giraffe1", "artie" ],
"days" : [ "T", "F" ],
"enrollee_info" : [
{ "_id" : 1, "name" : "artie", "joined" : ISODate("2016-05-01T00:00:00Z"), "status" : "A" },
{ "_id" : 3, "name" : "giraffe1", "joined" : ISODate("2017-10-01T00:00:00Z"), "status" : "A" }
]
}
How would you write this in Java with MongoDB?

How to update multiple fields(array field and normal field) in a single document of mongo db at a time using JAVA?

I want to update request fields only in an array using java.This is my existing document in mongo db:
{
"_id": "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner": "Self",
"Account_Name": "IC",
"Lead_Source": "Callbox",
"Opportunity_Name": "name1 ",
"Stage": "Proposal",
"Stage_Status": "A",
"1555570551211": [],
"1555556165153": [],
"1555556059584": [{
"id": "1557389940585",
"Notes": "Note 1"
},
{
"id": "1557389945398",
"Notes": "Hi Bobby "
},
{
"id": "1557389978181",
"Notes": "Spoken to Bobby."
},
{
"id": "1557389990159",
"Notes": "plan to call on 29/Apr"
}
],
"createdBy": "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate": "1562911250917"
}
Request payload:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Stage_Status" : "I",
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
}
]
}
I am trying to update "Stage_Status" and "1555556059584.Notes" at a time using $set.I am able to update "Stage_Status" but "1555556059584" array is going to reset with what i have updated with last one.
expected output:
{
"_id" : "6691e5068dwe335w42cb0a699650f",
"Opportunity_Owner" : "Self",
"Account_Name" : "IC",
"Lead_Source" : "Callbox",
"Opportunity_Name" : "name1 ",
"Stage" : "Proposal",
"Stage_Status" : "I",
"1555570551211" : [],
"1555556165153" : [],
"1555556059584" : [
{
"id" : "1557389940585",
"Notes" : "updated note 123"
},
{
"id" : "1557389945398",
"Notes" : "Hi Bobby "
},
{
"id" : "1557389978181",
"Notes" : "Spoken to Bobby."
},
{
"id" : "1557389990159",
"Notes" : "plan to call on 29/Apr"
}
],
"createdBy" : "2c18b8dbb7d74a41a66f53a90117480a",
"createdDate" : "1562911250917"
}
can any one please help me to figure it out in java.
I guess you wanted to update Stage_Status and 1555556059584.Notes at Once .
here is a demo about it
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "bigbang", "courses" : [ { "name" : "en", "classRoom" : "9001" }, { "name" : "math", "classRoom" : "1001" } ] }
> db.student.update({name:'bigbang','courses.name':'en'},{ $set: {'courses.$.classRoom':'1009',name :"course"} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : ObjectId("5d2c09ea8ed60ae70d3dd76b"), "name" : "course", "courses" : [ { "name" : "en", "classRoom" : "1009" }, { "name" : "math", "classRoom" : "1001" } ] }
the java demo is like this
collection.updateOne(and(eq("Stage_Status","A"),eq("1555556059584.id","1557389940585")),new Document("$set" ,new Document("Stage_Status","YOUR_NEW_VALUE").append("1555556059584.$.Notes","YOUR_NEW_VALUE")));
you must set the 1555556059584.id to let the diver know which element to be update .

mongo $near command on Nested Array

{
"merchantId" : "M168976258",
"catalogTypeId" : "catalogTypeProduct",
"items" : [
{
"name" : "Product 1",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
},
{
"name" : "Product 2",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
},
{
"name" : "Product 3",
"location" : {
"type" : "Point",
"coordinates" : [
0,
0
]
}
}
}
I able to Perfrom mongo near command on document which is having single location
using below command
db.abc.find({
location :{
$near : {
$geometry : {
index : "Point" ,
coordinates : [19.1, 72.89]
},
$maxDistance : 10000
}
}
})
but i'm not able to perform on document which having nested array can anybody help me out to find out problem
By running this query i get following error
db.catalogForAdminAndMerchant.find({
"items.location" :{
$near : {
$geometry : {
index : "Point" ,
coordinates : [19.1, 72.89]
},
$maxDistance : 10000
}
}
})
o/p is
planner returned error: unable to find index for $geoNear query
but have created the index
by running db.catalogForAdminAndMerchant.getIndexes() i get
/* 1 */
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "catalog-db.catalogForAdminAndMerchant"
},
/* 2 */
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "CatalogForAdminAndMerchant_TextIndex",
"ns" : "catalog-db.catalogForAdminAndMerchant",
"weights" : {
"items.name" : 3
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 3
},
/* 3 */
{
"v" : 2,
"key" : {
"address.items[i].location" : "2dsphere"
},
"name" : "address.items[i].location_2dsphere",
"ns" : "catalog-db.catalogForAdminAndMerchant",
"2dsphereIndexVersion" : 3
}

How can we count the number of items in arraylist from different documents in mongodb java?

Assuming I have these documents:
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "blue", "purple" ] }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ "red", "yellow"] }
The result I would like is
blue : 2
red : 2
black : 1
purple : 1
yellow : 1
Is this possible to perform using the mongodb or do I need to manually implemented after getting colors array in Java? Hints or any help would be of very useful.
This is how I get the database and the collections
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoCollection<Document> collection = mongoClient.getDatabase("tweets")
.getCollection("tweet");
You can try the below aggregation.
db.collection.aggregate({$unwind:"$colors"},{$group: { _id:"$colors",count:{$sum:1} }})
The query will $unwind the array. From the docs
Deconstructs an array field from the input documents to output a
document for each element.
Response after $unwind stage.
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "blue" }
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "black" }
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", "colors" : "red" }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "blue" }
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", "colors" : "purple" }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "red" }
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", "colors" : "yellow" }
Next step is to $group the data on color while using $sum to count the colors
Final Output
{ "_id" : "yellow", "count" : 1 }
{ "_id" : "blue", "count" : 2 }
{ "_id" : "black", "count" : 1 }
{ "_id" : "red", "count" : 2 }
{ "_id" : "purple", "count" : 1 }
Java Update:
3.x Version
collection.aggregate( Arrays.asList(Aggregates.unwind("$colors"), Aggregates.group("$colors", Accumulators.sum("count", 1))));
2.x Version
collection.aggregate( Arrays.asList(new BasicDBObject("$unwind", "$colors"), new BasicDBObject("$group", new BasicDBObject("_id","$colors").append("count",new BasicDBObject("$sum", 1)))));

How to count number of occurence of specific field in a collection in Mongodb

I have my collection as shown below:
{
"_id" : NumberLong(366),
"file" : "xyz",
"clist" : {
"account" : "BFS",
"subAccount":"a"
},
},
{
"_id" : NumberLong(366),
"file" : "xyz",
"clist" : {
"account" : "BFS",
"subAccount":"b"
},
},
{
"_id" : NumberLong(366),
"file" : "xyz",
"clist" : {
"account" : "HC",
"subAccount":"c"
},
}
In that I have to group by account and count number of subAccount; for example:
{
account : "BFS",
subAccount : "b",
count : 1,
subAccount :"a",
count : 1
}
If for account BFS, subAccount b exists two times, then I should get output like this:
{
account : "BFS",
subAccount : "b",
count : 2,
subAccount : "a",
count : 1
}
May this help you...
db.coll.aggregate([ {
"$group" : {
"_id" : {
"account" : "$clist.account",
"subAccount" : "$clist.subAccount"
},
"count" : {
"$sum" : 1
}
}
}, {
$project : {
_id : 0,
"account" : "$_id.account",
"subAccount" : "$_id.subAccount",
"count" : "$count"
}
}, {
$group : {
_id : "$account",
"subaccounts" : {
"$push" : {
"subAccount" : "$subAccount",
"count" : "$count"
}
}
}
} ])

Categories

Resources