mongodb collection uuid how to update? - javascript

How to create collection in mongodb with specific uuid or update the uuid ?
db.runCommand( { listCollections: 1.0 })
"uuid" : UUID("8d1e5add-9e49-4ff5-af4f-abf12e40b078")
Adding details:
When I create a collection mongodb generate automatically uuid and if this is replicaSet the uuid is replicated to all SECONDARY members via the oplog:
PRIMARY> use test
PRIMARY> db.createCollection("theTest")
PRIMARY> use local
PRIMARY> db.oplog.rs.find({}).sort({$natural:-1})
{ "ts" : Timestamp(1632477826, 1), "t" : NumberLong(56), "h" : NumberLong("8154379731463656698"), "v" : 2, "op" : "c", "ns" : "test.$cmd", "ui" : UUID("7710a307-020a-48bf-916c-db94544f8586"), "wall" : ISODate("2021-09-24T10:03:46.145Z"), "o" : { "create" : "theTest", "idIndex" : { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.theTest" } } }
But I would like to know if there is an option this UUID to be created with command or updated ?
Maybe there is an option to apply oplog entry with modified UUID?
Thanks,

I have found the answer, for those who are interested here is the solution:
var uuid = UUID("a6c3c5c8-8424-4a06-96a1-4082c349c6f1");
var ops = [{ "op": "c","ns": "test.$cmd","ui": uuid,"o": {"create": "newTest","idIndex": {"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "test.newTest"} } }];
db.adminCommand({applyOps: ops});

Related

How do you parse a json object that has this format instead of an array

How do you properly parse a json object that has the following structure;
{
"cutoffTimes" : {
"85c46c49-99b6-47a1-9726-960c8fe6c337" : {
"id" : "85c46c49-99b6-47a1-9726-960c8fe6c337",
"customerId" : "fc0097ec-9c41-467f-9b81-50d9a07c65e8",
"time" : "17:00:00",
"deadlineCutoffType" : "TRANSMISSION"
},
"1784efdd-750f-4bae-b65f-179a4e8c28f3" : {
"id" : "1784efdd-750f-4bae-b65f-179a4e8c28f3",
"customerId" : "fc0097ec-9c41-467f-9b81-50d9a07c65e8",
"time" : "18:00:00",
"deadlineCutoffType" : "TRANSMISSION"
},
"86a2d573-e4f4-451a-930e-99922f1f229d" : {
"id" : "86a2d573-e4f4-451a-930e-99922f1f229d",
"customerId" : "fc0097ec-9c41-467f-9b81-50d9a07c65e8",
"time" : "21:30:00",
"deadlineCutoffType" : "TRANSMISSION"
}
}
I would typically do
let _times = JSON.parse({jsondoc});
console.log(`There are ${_times.cutoffTimes.length} times available`);
However, in this document, the cutoffTimes is not an array.
You could use Object.keys to check the length. It converts your object to array like ['85c46c49-99b6-47a1-9726-960c8fe6c337', '1784efdd-750f-4bae-b65f-179a4e8c28f3', ...]
console.log(`There are ${Object.keys(_times.cutoffTimes).length} times available`);

Firebase, orderByChild is not sorting

I'm trying to sort my snapshots by using orderByChild but this thing is not working.
FIREBASE RULES :
"rules": {
"community": {
"users": {
".read": true,
"$uid": {
".read": true,
".write": "$uid === auth.uid",
".indexOn": ["pseudo", "pseudoLower", "pseudoInverseLower", "films"]
}
}
}
}
DATA :
"community" : {
"users" : {
"Ab" : {
"films" : 200,
"filters" : 2,
"id" : "Ab",
"pseudoBase" : "AB",
"pseudoInverseLower" : "zy",
"pseudoLower" : "ab"
},
"Bc" : {
"films" : 692,
"filters" : 4,
"id" : "Bc",
"pseudoBase" : "King",
"pseudoInverseLower" : "prmt",
"pseudoLower" : "king"
},
"Ce" : {
"films" : 100,
"filters" : 5,
"id" : "a",
"pseudoBase" : "A",
"pseudoInverseLower" : "z",
"pseudoLower" : "a"
}
}
}
JS :
db.ref('community/users').orderByChild('films').once('value', snap => {})
In the user data you'll retrieve his pseudo (and the inverse), his films length and filters length.
I tried orderByChild('pseudoLower'), .orderByChild('films') and .orderByChild('pseudoInverseLower') but nothing changed.
I'm really stuck at this point... Maybe I forgot something?
You need to convert the resultant snapshot into an array of children – this can be done using the snapshot forEach method and this will iterate the children in order of the child key provided in the query. The users will lose the order they were received in if you print the snapshot value.
async function getCommunityUsers(filter) {
const usersRef = admin.database().ref('community/users')
const snapshot = await usersRef.orderByChild(filter).once('value')
let users = []
snapshot.forEach(child => {
users.push({
key: child.key,
...child.val()
})
return false
})
return users
}

How to increment existing value in MongoDB

I am using Stitch platform by MongoDB. I want to store a value and a count associated with that value in the database. Now the value may not be present for the first time, so I would like to insert the value with count = 1.
I can use update() to update the existing value of count using $inc or I can use upsert() to add the value in the database.
Now, the thing is, I have a map of my values and the count, and I want to insert(update/upsert) all at once. I don't want to put a load on the network.
I was using insertMany() to insert the map at once but it clearly doesn't updates the value.
So is it possible to do so?
P.S. I am using javascript for the same.
According to MongoDb 3.6:
db.collection.update(query, update, options)
Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.
The meaning is that you can upsert multiple documents using update.
First you should create array from your map that contains only the value.
const arrayOfValues = ['value_01', 'values_02'];
Then you should use the upsert + multi options on the update method:
db.foo.update({value: { $in: arrayOfValues}}, {$inc: {count:1}}, { upsert: true, multi: true });
Test output:
> db.createCollection("test");
{ "ok" : 1 }
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}];
... );
2017-12-31T12:12:18.040+0200 E QUERY [thread1] SyntaxError: missing ) after argument list #(shell):1:61
> db.test.insertMany([{value: "a"}, {value: "b"}, {value: "c"}]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5a48b8061b98cc5ac252e435"),
ObjectId("5a48b8061b98cc5ac252e436"),
ObjectId("5a48b8061b98cc5ac252e437")
]
}
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b" }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c" }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 1 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 1 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
> db.test.find();
{ "_id" : ObjectId("5a48b8061b98cc5ac252e435"), "value" : "a", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e436"), "value" : "b", "count" : 2 }
{ "_id" : ObjectId("5a48b8061b98cc5ac252e437"), "value" : "c", "count" : 2 }
> db.test.update({value: { $in: ["a", "b", "c"]}}, {$inc: {count:1}}, { upsert: true, multi: true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Hope it was helpful :)

Compare two arrays for similar values javascript

I have two arrays, one I am getting from form request and the other I am getting from a mongoDb query. I want to look for all the items passed in request parameters inside the result obtained in mongodb array.
var userIdArr = ["6fbeb3e28de42200e7e7d36", "56fbde9be618221c1d67f01"];
var mongoDbResultsArr= [
{"_id": "56fce5bf7031bd482abdfb8a",
"userIds": "[56fbeb3e28de42200e7e7d36, 56fbde9be618221c1d67f010]"
},
{"_id": "56fd2c22ea0f3664156685ac",
"userIds": "[56fbeb3e28de42200e7e7d36, 56fbde9be618221c1d67f010, 56f53491886e496e32c68b00]"
}
]
Basically I want to search if the values given in userIdArr exists in the 'userIds' key of mongoDbResultsArr. Also if this can be done by writing just mongodb query, or any other better way.
This is how my schema looks like
{
"_id" : ObjectId("56fd2c22ea0f3664156685ac"),
"startDateTime" : ISODate("2016-03-31T08:34:59.000Z"),
"endDateTime" : ISODate("2016-03-31T08:34:59.000Z"),
"productId" : "#789990#2",
"applicableThemes" : [
"red"
],
"userIds" : "[56fbeb3e28de42200e7e7d36, 56fbde9be618221c1d67f010, 56f53491886e496e32c68b00]",
"price" : 45,
"dealType" : 1,
"photos" : {
"dealimageUrl3" : "http://mailers.shopping.indiatimes.com/shopstatic/shopping/images/diwali2013/banner.jpg",
"dealimageUrl2" : "http://mailers.shopping.indiatimes.com/shopstatic/shopping/images/diwali2013/banner.jpg",
"dealimageUrl1" : "http://mailers.shopping.indiatimes.com/shopstatic/shopping/images/diwali2013/banner.jpg"
},
"dealDescription" : "Bang Bang deal!!",
"dealName" : "Christmas Special Offer",
"storeId" : "56f5339fe99b1a294818ecbe",
"__v" : 0
}
and I am using mongoose ORM.

Group Array into a more complex Array

I create an array of Objects from a database query and call the
array jobListRecords. There are multiple records in the array created that have the same "customerID" and "name".
I would like to create a new array that has one record for each customer with a new field , "jobArray", that contains another array of all of that customers services. (see sortCustomer array down below)
An example of the initial array:
jobListRecords = [
{
"customerID" : "1",
"name" : "Larry Bird",
"serviceID" : "101",
"serviceName" : "Dog Walking"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
Desired Result
sortCustomer Example:
sortCustomer = [
{
"customerID" : "1",
"name" : " Larry Bird",
"jobArray" : [
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
},
{
"customerID" : "2",
"name" : "Andrew Luck",
"jobArray" : [
{
"serviceID" : "202",
"serviceName" : "Baby Sitting"
},
{
"serviceID" : "101",
"serviceName" : "Dog Walking"
}
]
}
Is their a simple or efficient way of solving this without having to iterate through all the data 3+ times. Thank You for your time, below is one of the several things I tried.
I tried solving this using one example I found but it grouped all the serviceIDs together which is not what I need.
Example that DID NOT work that I tried.
jobListGrouped = _
.chain(jobListRecords)
.groupBy('customerID')
.map(function(value, key) {
return {
CustomerID: key,
services: _.pluck(value, 'serviceID')
}
})
.value();
You're plucking only the serviceIDs into that array. Instead, you would need to do something like
.map(function(values, key) {
return {
customerID: key,
name: values[0].name.
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
or even more explicit
.map(function(values, key) {
return _.extend(_.omit(values[0], 'serviceID', 'serviceName'), {
services: _.map(values, _.partial(_.pick, _, 'serviceID', 'serviceName'))
}
})
(where that partial call is the same as function(value) { return _.pick(value, 'serviceID', 'serviceName'); })

Categories