Mongo Upsert $in values from Find That were Not found - mongodb

I have to run mongo updates for employee id linked to a supervisorId (That's an oversimplification, but its the gist of what I need). The find uses a list of employee ids, and if the employee id is not found, I have an upsert to add the data. However the issue is I'm not getting the employee id in the upsert. Is it possible to upsert values from the $in array?
Eg:
db.collection.update({
empId:{
$in:['EMP1','EMP2','EMP3']
}
},
{$set: {SupervisorId:'SUP25'}},
{upsert:true},
{multi:true})
If I run this query I get one new doc with _id and SupervisorId:
{
"_id" : ObjectId("5e56ece8b0ae3537d0261ghg"),
"SupervisorId" : "SUP25"
}
I would like to get this in my upserts:
{
"_id" : ObjectId("5e56ece8b0ae3537d0261ghg"),
"SupervisorId" : "SUP25"
"EmpId": "EMP1"
}
I'm still getting comfortable with mongo, but is this even possible with an upsert? If not possible, are there any options for something similar?
MongoDB version 2.9.1

Related

How to get the last unique transactions from a collection in MongoDB

I have a collection that contains the following fields: agentId, postBalance, preBalance, etc. I want to fetch the last unique record for an agent that contains the field stated earlier based on a date filter.
db.transaction.find(
{
"createdAt" : {
"$gte": ISODate("2022-09-01T00:00:00Z"),
"$lt": ISODate("2022-09-02T00:00:00Z")
}
},
{
“agentId”: 1,
“walletBalance”: 1
}
)
The query above returns duplicate values and not the latest one. How best do I optimise this query. I am using Mongo Compass so I don't mind any query that comes in that format. I have read up on $last, $natural but they don't seem to solve my issue.
Have you tried to add sort by "createdAt" and limit of 1, or just using findOne method with same sort?

Mongodb: What is the best way to search multiple collections for the same field in one query

I inherited a bunch of collections and each of them have fields in common.
Is there a way to query the "EMAIL" field in collection A and Collection B ....or Am I stuck with iterating through the collections programmatically ?
db.colA.find({"EMAIL":"joe#doe.com"})
Collection A :
{ "_id" : ObjectId("58197fc91b69ba68721d4148"), "UUID" : "0b6827f2-9384-11e0-8f4a-b8ac6f949be6", "EMAIL" : "JOHNDOE#YAHEE.COM", "FNAME" : "JOHN", "LNAME" : "DOE"}
Collection B:
{ "_id" : ObjectId("4ed234423654fea654a654f2"), "SOURCE" : "65488451522", "EMAIL" : "JOHNDOE#YAHEE.COM", "FN" : "JOHN", "DOB":"05/13/1967"}
Expected behavior: the search query would returned both records.
Well, why not query Col A and Col B .. I have 17 collections in the DB, one query would be great.
You can use the aggregation lookup to achieve this:
db.colA.aggregate([
{
$lookup:
{
from: "colB",
localField: "EMAIL",
foreignField: "EMAIL",
as: "connected_query"
}
}
])
You will then have a field called connected_query in your results that refer to colB results that have the same email as colA.
You can't do this in a single query with your current collections.
You may be able to achieve this with DBRefs, but it will soon be deprecated (if not already), so don't use it unless it's absolutely necessary.
Even if running the same query on 17 distincts collections is not very elegant, I guess this is still the best option
If you are talking about joins, $lookup has been enabled in mongo latest version. Java doc: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
There's no way to do that. You're stuck to having to do that programmatically. Although MongoDB has embedded documents and an 'entity' might be scatted in many collections, there should be one collection which represents the complete entity
For example, you might have a UserProfile collection but snippets of user profile might be embedded in other collections. In that case when you need the complete user's profile, you query it straight from UserProfile collection.

Mongo DB find() query error

I am new to MongoDB. I have a collection called person. I'm trying to get all the records without an _id field with this query:
db.person.find({}{_id:0})
but the error is
syntax error: unexpected {
but if i write
db.person.find()
it works perfectly.
Consider following documents inserted in person collection as
db.person.insert({"name":"abc"})
db.person.insert({"name":"xyz"}
If you want to find exact matching then use query as
db.person.find({"name":"abc"})
this return only matched name documents
If you want all names without _id then use projeciton id query as
db.person.find({},{"_id":0})
which return
{ "name" : "abc" }
{ "name" : "xyz" }
According to Mongodb manual you have little wrong syntax, you forgot to give comma after {}
Try this :
db.person.find({}, { _id: 0 } )

Mongo DB Update to a sub array document

I have a structure
{
"_id" : ObjectId("562dfb4c595028c9r74fda67"),
"office_id" : "123456",
"employee" : [
{
"status" : "declined",
"personId" : "123456",
"updated" : NumberLong("1428407042401")
}
]
}
This office can have multiple persons.Is there a way if I want to update the employee status for all the person under that specific office_id to say "approved".I am trying the same through plain mongo java driver.What I am trying is get all the office id using a query builder , then iterate over the list and save the document.Somewhat I am not satisfied with the iterative approach(fetch,iterate and save ) that I am following.Please suggest if there is alternative way.
You can update using the $ positional operator:
db.collection.update(
{
"office_id" : "123456",
"employee.status": "declined"
},
{
"$set": { "employee.$.status": "approved" }
}
);
The positional operator saves the index (0 in the case above) of the element from the array that matched the query. This means that if you knew the position of the element beforehand (which is nearly impossible in a real life case), you could just change the update statement to: {"$set": {"employee.0.status": "approved"}}.
Please note that the $ positional operator (for now) updates the first relevant document ONLY, there is a JIRA ticket for this.
EDIT:
Using the Java driver, the above update may be done like so (untested):
BasicDBObject update = new BasicDBObject();
BasicDBObject query = new BasicDBObject();
query.put("office_id", "123456");
query.put("employee.status", "declined");
BasicDBObject set = new BasicDBObject("$set", update);
update.put(""employee.$.status", "approved");
collection.update(query, set);

Unable to get the value of a MongoDB key

2 days old to Mongo, so bear with me.
I have a collection from which, I only want to retrieve specific values contingent to another key existing in the MongoDB environment.
Here is what I am doing:
db.results.find({'someKeyThatShouldExist':{$exists:true}}, {"parentKey.childKey.theKeyWoseValueIwant":1}
This yields data in the following format for me:
{ "_id" : ObjectId("532a2c2b6803fa486b8b456a"), "parentKey" : { "childKey" : { "theKeyWhoseValueIWant" : 102982577 }}}.....
Now, all I really want is the value 102982577, not everything else.
How can I do this ?
You can suppress the _id by adding _id:0 to the projection criteria.
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)
To get just the value, you could do something like:
db.results.find(
{"someKeyThatShouldExist":{$exists:true}},
{_id:0, "parentKey.childKey.theKeyWoseValueIwant":1}
)[0].parentKey.childKey.theKeyWoseValueIwant