如何在mongodb中按引用字段查询?

时间:2019-02-12 02:40:53

标签: javascript node.js mongodb mongoose aggregation-framework

我有2个mongo模式:

用户:

   <p class="min-amount small">${{minAmount}}</p>

国家/地区:

{
  _id: ObjectId,
  name: String,
  country: ObjectId // Reference to schema Country
}

我想让所有用户的国家名是VietNam。

在这种情况下,我可以使用什么查询(仅查询用户)?

我想看起来像这样的SQL查询:

{
  _id: ObjectId,
  name: String
}

4 个答案:

答案 0 :(得分:1)

与关系数据库不同,这不是Mongo擅长的事情,并且在使用NoSQL时,通常应该以不同的方式构造模式。在这种情况下,您可以向debugger集合中添加一个countryName字段(并可能添加国家索引),以便查询user。 (而不是国家名称,使用iso-2国家/地区代码可能更有意义)

如果您确实需要进行“联接”,则可以使用$lookup operator in the aggregation pipeline -请记住,聚合的伸缩性不好,并且往往很难编写。

答案 1 :(得分:1)

您可以在mongodb 3.6 及更高版本

中使用以下聚合
db.country.aggregate([
  { "$match": { "name": "VietNam" } },
  { "$lookup": {
    "from": Users.collection.name,
    "let": { "countryId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [ "$country", "$$countryId" ] } } },
    ],
    "as": "users",
  }},
  { "$unwind": "$users" },
  { "$replaceRoot": { "newRoot": "$users" }}
])

答案 2 :(得分:0)

这里是我通常使用的代码:

Models / users.js


const mongoose = require("mongoose");
const Countries = require("./countries");

const UsersSchema = new mongoose.Schema({
    name: Sting,
    country: Countries.schema
});

module.exports = mongoose.model("Users", UsersSchema);

controllers / users.js

const express = require("express");
const router = express.Router();
const Users = require("../models/users");

router.post("/register", async(req, res) => {
    try{
      const Me = await Users.create({name: req.body.name, country: req.body.country})
      /* If you make the request correctly on the frontend req.body.name is a 
         string and req.body.country is an object with one property, it's name */
      res.status(200).json({
          data: Me
      });
    }
    catch(err){
      res.status(400).json({message:err.message})


由于子模式是一个对象,因此您将其称为Me.country.name。希望这会有所帮助!

答案 3 :(得分:0)

如果要关联2个或更多集合,则必须定义集合的引用对象

我的解决方案,请检查此https://mongoosejs.com/docs/populate.html