  Using the near-IR spectroscopy of the MOSFIRE Deep Evolution Field (MOSDEF)
survey, we investigate the role of local environment in the gas-phase
metallicity of galaxies. The local environment measurements are derived from
accurate and uniformly calculated photometric redshifts with well-calibrated
probability distributions. Based on rest-frame optical emission lines,
[NII]$\lambda6584$ and H$\alpha$, we measure gas-phase oxygen abundance of 167
galaxies at $1.37\leq z\leq1.7$ and 303 galaxies at $2.09\leq z\leq2.61$,
located in diverse environments. We find that at $z\sim1.5$, the average
metallicity of galaxies in overdensities with $M_*\sim10^{9.8}M_\odot,
10^{10.2}M_\odot$ and $10^{10.8}M_\odot$ is higher relative to their field
counterparts by $0.094\pm0.051$, $0.068\pm0.028$ and $0.052\pm0.043$ dex,
respectively. However, this metallicity enhancement does not exist at higher
redshift, $z\sim2.3$, where, compared to the field galaxies, we find
$0.056\pm0.043$, $0.056\pm0.028$ and $0.096\pm 0.034$ dex lower metallicity for
galaxies in overdense environments with $M_*\sim10^{9.8}M_\odot,
10^{10.2}M_\odot$ and $10^{10.7}M_\odot$, respectively. Our results suggest
that, at $1.37\leq z\leq2.61$, the variation of mass-metallicity relation with
local environment is small ($<0.1$dex), and reverses at $z\sim2$. Our results
support the hypothesis that, at the early stages of cluster formation, owing to
efficient gas cooling, galaxies residing in overdensities host a higher
fraction of pristine gas with prominent primordial gas accretion, which lowers
their gas-phase metallicity compared to their coeval field galaxies. However,
as the Universe evolves to lower redshifts ($z\lesssim2$), shock-heated gas in
overdensities cannot cool down efficiently, and galaxies become metal-rich
rapidly due to the suppression of pristine gas inflow and re-accretion of
metal-enriched outflows in overdensities.
