MongoDB search using $in array not working - arrays

I'm using MongoDB shell version: 2.4.8, and would simply like to know why a nested array search doesn't work quite as expected.
Assume we have 2 document collections, (a) Users:
{
"_id" : ObjectId("u1"),
"username" : "user1",
"org_ids" : [
ObjectId("o1"),
ObjectId("o2")
]
}
{
"_id" : ObjectId("u2"),
"username" : "user2",
"org_ids" : [
ObjectId("o1")
]
}
and (b) Organisations:
{
"_id" : ObjectId("o1"),
"name" : "Org 1"
}
{
"_id" : "ObjectId("o2"),
"name" : "Org 2"
}
Collections have indexes defined for
Users._id, Users.org_id, Organisations._id
I would like to find all Organisations a specific user is a member of.
I've tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : [myUser.org_ids] }})
yet it yields nothing as a result. I've also tried this:
> myUser = db.Users.find( { _id: ObjectId("u1") })
> db.Organisations.find( { _id : { $in : myUser.org_ids }})
but it outputs the error:
error: { "$err" : "invalid query", "code" : 12580 }
(which basically says you need to pass $in an array) ... but that's what I thought I was doing originally ? baffled.
Any ideas what I'm doing wrong?

db.collection.find() returns a cursor - according to documentation. Then myUser.org_ids is undefined, but $in field must be an array. Let's see the solution!
_id is unique in a collection. So you can do findOne:
myUser = db.Users.findOne( { _id: ObjectId("u1") })
db.Organisations.find( { _id : { $in : myUser.org_ids }})
If you are searching for a non-unique field you can use toArray:
myUsers = db.Users.find( { username: /^user/ }).toArray()
Then myUsers will be an array of objects matching to the query.

Related

Rename a sub-document field within an Array of an Document

I am trying to rename the particular child field inside an array of an collection in MONGODB
{
"_id" : Id("248NSAJKH258"),
"isGoogled" : true,
"toCrawled" : true,
"result" : [
{
"resultsId" : 1,
"title" : "Text Data to be writen",
"googleRanking" : 1,
"isrelated" : false
},
{
"resultId" : 2,
"title" : "Text Data",
"googleRanking" : 2,
"isrelated" : true
}]
**I need to rename "isrelated" to "related" ** from the collection document
Using mongo Version 4.0
I Tried :
db.collection_name.update({}, { $rename: { 'result.isrelated': 'result.related'} } )
But it didn't worked in my case
As mentioned in official documentation $rename not working for arrays.
Please check link below:
https://docs.mongodb.com/manual/reference/operator/update/rename/
But you can do something like this
let newResult = [];
db.aa1.find({}).forEach(doc => {
for (let i in doc.result) {
newResult.push({
"resultsId" : doc.result[i]['resultsId'],
"title" : doc.result[i]['title'],
"googleRanking" : doc.result[i]['googleRanking'],
"related" : doc.result[i]['isrelated'],
})
}
db.aa1.updateOne({_id: doc._id}, {$set: {result: newResult}});
newResult = []
})

Copy a field from one collection to another in mongodb with foreign key as mixed type

Although i have found a similar question on stackOverFlow MongoDB copy a field to another collection with a foreign key
I want to copy a field name from userdetails collection to user collection where userId in userDetails equals _id in user.
user collection
{
"_id" : ObjectId("5b97743bbff66e0be66283cc"),
"username" : "mmi_superadmin",
"accId" : "acc1"
}
{
"_id" : "c21d580ea3ca5c7a1664bd5feb57f0c8",
"username" : "client",
"accId" : "acc1"
}
userDetail collection
{
"_id" : ObjectId("5b97743bbff66e0be66283cd"),
"userId" : "5b97743bbff66e0be66283cc",
"name" : "mmi_superadmin"
}
{
"_id" : "5bab8a60ef86bf90f1795c44",
"userId" : "c21d580ea3ca5c7a1664bd5feb57f0c8",
"name" : "RAHUL KUMAR TIWARI"
}
Here is my query :
db.userDetails.find().forEach(
function(x) {
db.user.update( {_id :x.userId}, {$set: {name:x.name}});
}
);
This query is partially working. It only updates user documents where _id is of type string. User document with _id as ObjectId are not getting updated.
Please check your documents _id's (because in your example some _id's is not valid documents _id's. for example c21d580ea3ca5c7a1664bd5feb57f0c8 not a mongo _id) and use this query:
let usersIds = [];
db.user.find({"_id": {$type: 7}}).forEach(doc => {
usersIds.push(doc._id + '')
db.userDetail.find({
userId: {
$in: usersIds
}
}).forEach(doc => {
db.user.update(
{
"_id": ObjectId(doc.userId)
},
{
$set: {
"name": doc.name
}
},
{
multi: false,
upsert: false
}
)
})
})
if you have any question feel free to ask

Delete collection in mongodb

I have the following json file in mongodb:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"32a1fsd32asfd65asdf65" : {
...
},
"32a1fsd32asfd555" : {
}, ...
}
}
I want to perform a query and delete one of the two items. As a matter of fact, my database contains several users. Therefore, in order to retrieve the specific one from the mongodb i am performing the following:
How can I retrieve also a specific item and delete all its fields (for example 32a1fsd32asfd65asdf65)?
Based on the example document provided in your document it looks like you want to remove an attribute of the subdocument item.
You can use the $unset update operator:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "sfd65asdf65"
{$unset: {'item.sfd65asdf65': 1}}
)
Given the document provided in your question, the above command will cause that document to be updated to:
{
"_id" : ObjectId("59de156faf75d539b47e8db3"),
"user" : "user1",
"item" : {
"sd32asfd555" : {
...
}
}
}
If you want to remove the item attribute entirely then you would run:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// unset the attribute named "32a1fsd32asfd65asdf65"
{$unset: {'item': 1}}
)
And if you want to empty the item attribute (i.e. remove all of its attributes but retain the item attribute) then you would run this command:
db.getCollection('colName').update(
// find a specific document
{user: 'user1'},
// overwrite the "item" attribute with an empty sub document
{$set: {'item': {}}}
)
You can find more examples in the docs.
Say we have some users:
> db.test.insert( { _id: 1, user: "bob", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
> db.test.insert( { _id: 2, user: "fred", field1: 1, field2 :{ field3 : 2 } } )
WriteResult({ "nInserted" : 1 })
We can then use replaceOne to find the user and also then just replace the whole document, thus removing all the fields from that document:
> db.test.replaceOne( { user: "bob"}, { user: "bob" } )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Then our new documents will look like:
> db.test.find()
{ "_id" : 1, "user" : "bob" }
{ "_id" : 2, "user" : "fred", "field1" : 1, "field2" : { "field3" : 2 } }

String from document meets value of array

I've got an array of Project ID's, for example:
[ 'ExneN3NdwmGPgRj5o', 'hXoRA7moQhqjwtaiY' ]
And in my Questions collection, I've got a field called 'project', which has a string of a project Id. For example:
{
"_id" : "XPRbFupkJPmrmvcin",
"question" : "Vraag 13",
"answer" : "photo",
"project" : "ExneN3NdwmGPgRj5o",
"datetime_from" : ISODate("2017-01-10T08:01:00Z"),
"datetime_till" : ISODate("2017-01-10T19:00:00Z"),
"createdAt" : ISODate("2017-01-10T08:41:39.950Z"),
"notificationSent" : true
}
{
"_id" : "EdFH6bo2xBPht5kYW",
"question" : "sdfadsfasdf",
"answer" : "text",
"project" : "hXoRA7moQhqjwtaiY",
"datetime_from" : ISODate("2017-01-11T11:00:00Z"),
"datetime_till" : ISODate("2017-01-11T17:00:00Z"),
"createdAt" : ISODate("2017-01-10T10:21:42.147Z"),
"notificationSent" : false
}
Now I want to return all documents of the Questions collection, where the Project (id) is one of the value's from the Array.
To test if it's working, I'm first trying to return one document.
Im console.logging like this:
Questions.findOne({project: { $eq: projectArray }})['_id'];
but have also tryed this:
Questions.findOne({project: { $in: [projectArray] }})['_id'];
But keep getting 'undefined'
Please try this.
Questions.find({project: { $in: projectArray }}) => for fetching all docs with those ids
Questions.findOne({project: { $in: projectArray }}) => if you want just one doc

MongoDB Update array in a document

I try to update arrays of multiple document with this query :
db.BusinessRequest.update({"DealTypes": { $exists: true }, "DealTypes.DisplayName": "Minority trade sale" }, {$set:{"DealTypes.$.DisplayName":"Minority"}}, false,true );
but when there is a match, it only updates the first row of my array whereas the displayName does not match with the first.
I use IntelliShell of MongoChef software.
My document looks like this :
{
"_id" : BinData(4, "IKC6QJRGSIywmKTKKRfTHA=="),
"_t" : "InvestorBusinessRequest",
"Title" : "Business Request 000000002",
"DealTypes" : [
{
"_id" : "60284B76-1F45-49F3-87B5-5278FF49A304",
"DisplayName" : "Majority",
"Order" : "001"
},
{
"_id" : "64A52AFE-2FF5-426D-BEA7-8DAE2B0E59A6",
"DisplayName" : "Majority trade sale",
"Order" : "002"
},
{
"_id" : "C07AE70D-4F62-470D-BF65-06AF93CCEBFA",
"DisplayName" : "Minority trade sale",
"Order" : "003"
},
{
"_id" : "F5C4390A-CA7D-4AC8-873E-2DC43D7F4158",
"DisplayName" : "Equity fund raising",
"Order" : "004"
}
]
}
How can I achieve this please ? Thanks in advance
EDIT :
This line works :
db.BusinessRequest.update({"DealTypes": { $exists: true }, "DealTypes": { $elemMatch: {"DisplayName": "Majority trade sale"}}}, {$set:{"DealTypes.$.DisplayName":"Majority"}}, false,true );
Please try this :
db.BusinessRequest.find().forEach( function(doc) {
do {
db.BusinessRequest.update({{"DealTypes": { $exists: true }, "DealTypes.DisplayName": "Minority trade sale" },
{$set:{"DealTypes.$.DisplayName":"Minority"}});
} while (db.getPrevError().n != 0);
})
or
You cannot modify multiple array elements in a single update operation. Thus, you'll have to repeat the update in order to migrate documents which need multiple array elements to be modified. You can do this by iterating through each document in the collection, repeatedly applying an update with $elemMatch until the document has all of its relevant comments replaced.
db.BusinessRequest.update({"DealTypes": { $exists: true }, "DealTypes": { $elemMatch: {"DisplayName": "Majority trade sale"}}}, {$set:{"DealTypes.$.DisplayName":"Majority"}}, false,true );
If you need efficiency in the search then I suggest you to normalise schema where each row is kept in separate document.
Please execute the following script in your mongo shell :
db.BusinessRequest.find({"DealTypes":{$exists:true}}).forEach(function(item)
{
for(i=0;i < item.DealTypes.length;i++)
{
if(item.DealTypes[i].DisplayName === 'Minority trade sale'){
item.DealTypes[i].DisplayName = 'Minority';
}
}
db.BusinessRequest.save(item);
});
Last two arguments in your update have a problem.
This is the form of update() method in mongodb
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
I believe your update should be like this;
db.BusinessRequest.update
( {"DealTypes": { $exists: true }, "DealTypes.DisplayName": "Minority trade sale" }
, {$set:{"DealTypes.$.DisplayName":"Minority"}}
{ upsert : false, multi : true });

Resources