mardi 12 janvier 2021

How to compare Hostnames and boolean values in JavaScript with if/else to execute in Mongo Shell?

I need to compare Host names from two expressions in Java script using if/else(to be executed in Mongo Shell) and print the result.

Snippet I:

for Ex: In MongoDB,

i) rs.isMaster().primary.split(":").shift() returns primary host name as shown below:

MongoDB Enterprise replica001:PRIMARY> rs.isMaster().primary.split(":").shift()

TEST-HOST1

ii) db.hostInfo().system.hostname returns current host name

MongoDB Enterprise replica001:PRIMARY> db.hostInfo().system.hostname

TEST-HOST1

Now in general terms:

if current_hostname= Primary_host_name {
  print('Node connected is Primary');
} else {
  print('Node connected is NOT Primary');
}

Code:

if(rs.isMaster().primary.split(":").shift() == db.hostInfo().system.hostname) {
  print("Node Connected is Primary");
} else {
  print("Node Connected is NOT Primary");
}

But in the output I am getting below error:

2021-01-13T01:01:29.016+0530 E QUERY    [js] SyntaxError: expected expression, got end of script @(shell):1:77

Node Connected is Primary

2021-01-13T01:01:29.017+0530 E QUERY    [js] SyntaxError: expected expression, got keyword 'else' @(shell):1:0

Node Connected is NOT Primary

Snippet II:

The following code also returns same error:

if(rs.isMaster().ismaster == true) {
  print("Node Connected is Primary");
} else {
  print("Node Connected is NOT Primary");
}

Can some one correct the syntax and help me get the code executed.

Aucun commentaire:

Enregistrer un commentaire