Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

mongodb - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

seems isMaster & hostInfo giving me different values in my home lab:

kiko:SECONDARY> if(rs.isMaster().ismaster == true) {   print("Node Connected is Primary"); } else {   print("Node Connected is NOT Primary"); }
Node Connected is NOT Primary
kiko:SECONDARY> if(rs.isMaster().primary.split(":").shift() == db.hostInfo().system.hostname) {   print("Node Connected is Primary"); } else {   print("Node Connected is NOT Primary"); }
Node Connected is NOT Primary
kiko:SECONDARY> if(rs.isMaster().ismaster == true) {   print("Node Connected is Primary"); } else {   print("Node Connected is NOT Primary"); }
Node Connected is Primary
kiko:PRIMARY> if(rs.isMaster().primary.split(":").shift() == db.hostInfo().system.hostname) {   print("Node Connected is Primary"); } else {   print("Node Connected is NOT Primary"); }
Node Connected is NOT Primary
kiko:PRIMARY> db.hostInfo().system.hostname
titan-lab:30001
kiko:PRIMARY> rs.isMaster().primary
localhost:30001
kiko:PRIMARY> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...