I have a mongo collection with data as follows:
(userid, orgid, some_attr)
g#gmail.com, 12345, 'xxxxxx'
Same collection also contains:
(orgid, some_attr)
12345, 'yyyyy'
Now when I am updating data I may query on (userid, orgid) or (orgid).
My issue is:
when I update using query (orgid), it finds the record with userid and updates that. I dont want that.
How can I query on (orgid) but exclude all documents which contains
(userid, orgid).
For eg:
when I query { orgid : 12345 } it should only return { 12345, 'yyyyy' } and not
{ 'g#gmail.com' , 12345, 'xxxxx' }
Please provide pointers.
http://docs.mongodb.org/manual/reference/operator/query/exists/
Change your query:
{ orgid : 12345, userid: {$exists: false} }
Related
How can I find the value of ObjectId in whole database for any field in mongo ,
it might be use in some collections for various fields as a reference?
"fourk_runs": [{
"Objectid": "6299b9f00f09ff045cc15d"
}],
"fourk_pass_fail": [{
"Objectid": "6299b9f00f09ff045cc152"
}],
"dr_runs": [{
"Objectid": "6299b9f00f09ff045cc154"
}],
I try this command , but it does not work
db.test.find( { $text: { $search: "4c8a331bda76c559ef04" } } )
In MongoDB, the references are mostly used for the normalization process. The references from the children's table (usually an ObjectID) are then embedded in the parent table. When reading the information, the user has to perform several queries in order to retrieve data from multiple collections.
For example, we will take the next two collections, parts and products. A product will contain many parts that will be referenced in the product collection.
parts Collection:
db.parts.findOne()
{
_id : ObjectID('1111'),
partno : '7624-faef-2615',
name : 'bearing',
price: 20,000
}
products Collection:
db.products.findOne()
{
name : 'wheel',
manufacturer : 'BMW',
catalog_number: 1134,
parts : [ // array of references to Part documents
ObjectID('1111'), // reference to the bearing above
ObjectID('3f3g'), // reference to a different Part
ObjectID('234r'),
// etc
]
}
To receive the parts for a particular product, we will first have to fetch the product document identified by the catalog number:
db.products.findOne({catalog_number: 1134});
Then, fetch all the parts that are linked to this product:
db.parts.find({_id: { $in : product.parts } } ).toArray();
I have Mongo document
{
"_id" : ObjectId("5e4c4c0935f4115dfc5540c2"),
"code" : "ABC"
}
and as per other SO threads looks like doing regex on Id is not possible as it has hexString. So I am querying with ObjectId
#Query("{'code': {$regex : ?0, $options: 'i'}, '_id': ?1}")
Page<Pack> findByCodeAndId(String code, ObjectId objectId, Pageable pageable);
now as the query paramets or optional, I have check if the passed id is valid before converting it to ObjectId
ObjectId objectId = null;
if (ObjectId.isValid(id)) {
objectId = new ObjectId(id);
}
now for the request {code: null, id: null} I want to bring first 10 documents as these are optional but the query is not working when it is passed null as ObjectId
Also tried ObjectId objectId = new ObjectId() but it is generating a random haxString and giving empty records when id is null
Below is my collection
[{documentId: 123, id: uniqueValue }]
Expected result
[{documentId: 123, id: id1,uniqueKey: uniqueValue }]
How do I refer "id" column for currently updating records, also id column can be anything for which my outer query is giving me the column name
db.supplier.updateMany( { documentId : 123}, { $set: { "uniqueKey": id} } );
so in above query "id" is coming like outerObject.mapping.idColumn which I want to substitute in above query.
The whole point of doing this, is to create index on column, and current collection does not have fixed column name on which I want to fire a query
Example
There are two collections collectionOne and collectionTwo
for each document in collectionOne there are multiple document in collectionTwo. The docId is used for lookup.
collectionOne
[{
docId :123,
col1 : lookupColumn
metaData: "some metaData",
extra : "extra columns"
}, ... ]
collectionTwo
[{
docId :123,
lookupColumn:"1",
a:"A",
b:"B" ....
},
{ docId :123,
lookupColumn:"2",
a:"A",
b:"B" ....
}
{ docId :123,
lookupColumn:"3",
a:"A",
b:"B" ....},.....]
lookupColumn in collectionTwo may have different name and mapping of that name is given in collectionOne by col1 field (which is always same), in this example col1 value is lookupColumn so I want to create a column newKey and copy value of lookupColumn into it.
So I came up with below Query
db.collectionOne.find({}).forEach(function(obj) {
if(obj.columns) {
existingColumn =obj.columns.col1;
db.collectionTwo.updateMany( { docId: obj.docId}, { $set: { "newKey": existingColumn} } );
}
}
problem is I am not able to pick an existing column name using variable existingColumn, I have tried using $ as well, which inserts $"existingColumn" as newKey value.
I have updated query with one more loop over collectionTwo but I feel that in optimized and unnecessary.
To go from
{documentId: 123, id: uniqueValue }
to
{documentId: 123, id: id1, uniqueKey: uniqueValue }
Use the pipeline style of update, which lets you use aggregation syntax:
db.collection.update({documentId: 123}, [{$set:{uniqueKey:"$id", id:"id1"}}])
EDIT
The latest edit to the question makes this a lot more clear.
You were almost there.
In MongoDB 4.2, the second argument to updateMany accepts either an update document like you were using:
db.collectionTwo.updateMany( { docId: obj.docId}, { $set: { "newKey": existingColumn} } );
Or it can accept an aggregation-like pipeline, but not all stages are available. For this use, if you make that second argument an array so that it is recognized as a pipeline, you can use the "$variable" structure. Since you already have the field name in a javascript variable, prepend "$" to the fieldname:
db.collectionTwo.updateMany( { docId: obj.docId}, [{ $set: { "newKey": "$" + existingColumn} }] );
I have a JSON structure at first insertion as
collection.insert(query.query, function(err, docs) {
callback(err,docs);
dbCon.close();
});
JSON Structure:
"employees":[
{"_id":1, "lastName":"Doe"},
{"_id":2, "lastName":"Smith"},
{"_id":3,"lastName":"Jones"}
]
When I first insert this JSON into mongodb, it gets inserted without any errors.
When I try insert again on the same database, with below JSON
"employees":[
{"_id":2, "lastName":"Smith"},
{"_id":5, "lastName":"Peter"},
{"_id":6,"``lastName":"James"}
]
Now the mondo db is throwing duplicate key error.
Is there any way where I can omit the "_id":2 and insert "_id":5 and "_id":6 into mongo?
Please help me..
You can perform an upsert in your case :
db.people.update(
{ name: "Andy" },
{
name: "Andy",
rating: 1,
score: 1
},
{ upsert: true }
)
If the first query gets a blank collection, that it will insert the data in this case if a Recrod with name Andy is not there, it will insert one.
In the first time, you insert a document
{"_id":2, "lastName":"Smith"}.
In the second time , you insert a document {"_id":2, "lastName":"Smith"}.
Their ids are the same ,not unique.
Suggest create id automatically by mongdb.
You can add the following code:
collection.findOne({"_id":2}.exec(function(err,result){
if(!result){
collection.insert(XXX);
}
}));
Is there such a query that gets multiple fields, and returns which of these exists in the collection?
For example, if the collection has only:
{id : 1}
{id : 2}
And I want to know which of [{id : 1} , {id : 3}] exists in it, then the result will be something like [{id : 1}].
You are looking for the $in-operator.
db.collection.find({ id: { $in: [ 1, 3 ] } });
This will get you any documents where the id-field (different from the special _id field) is 1 or 3. When you only want the values of the id field and not the whole documents:
db.collection.find({ id: { $in: [ 1, 3 ] } }, { _id: false, id:true });
If you want to check provided key with value is present or not in collection, you can simply check by matching values and combining conditions using $or operator.
By considering id is different than _id in mongo.
You can use $or to get expected output and query will be as following.
db.collection.find({$or:[{"id":1},{"id":3}]},{"_id":0,"id":1})
If you want to match _id then use following query:
db.collection.find({$or:[{"_id":ObjectId("557fda78d077e6851e5bf0d3")},{"_id":ObjectId("557fda78d077e6851e5bf0d5")}]}