Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 查询节点mongodb中对象的嵌套数组_Node.js_Mongodb_Mean Stack - Fatal编程技术网

Node.js 查询节点mongodb中对象的嵌套数组

Node.js 查询节点mongodb中对象的嵌套数组,node.js,mongodb,mean-stack,Node.js,Mongodb,Mean Stack,我是node+Mongo的新手。我在mongoDB中有以下结构的数据: var data = [{ id:1, createdBy:"test", sharedTo:["john","shekar"] }, { id:2, createdBy:"steve", sharedTo:["test","shekar"] }, { id:3, createdBy:"mark", sharedTo:[

我是node+Mongo的新手。我在mongoDB中有以下结构的数据:

     var data = [{
    id:1,
    createdBy:"test",
    sharedTo:["john","shekar"]
    },
    {
    id:2,
    createdBy:"steve",
    sharedTo:["test","shekar"]
    },
{
    id:3,
    createdBy:"mark",
    sharedTo:["steve","test"]
    },
{
    id:4,
    createdBy:"akuni",
    sharedTo:["john","shekar","mark"]
    },
{
    id:5,
    createdBy:"test",
    sharedTo:["mark","shekar"]
    },
{
    id:6,
    createdBy:"mark",
    sharedTo:["test","akuni"]
    }]
我想通过查询来获取用户“test”创建的所有记录以及共享给“test”的记录。我该怎么做

预期结果:

[{
    id:1,
    createdBy:"test",
    sharedTo:["john","shekar"]
    },

{
    id:5,
    createdBy:"test",
    sharedTo:["mark","shekar"]
    },
{
    id:6,
    createdBy:"mark",
    sharedTo:["test","akuni"]
    }]
我试过类似的东西

var user = "test";
    data.find({createdBy:user,sharedTo:{$elemMatch:[user]}},function(err, resp){

    });
但是它返回空的

使用mongodb的查询操作符

db.collection.find({
  $or: [
    { createdBy: "test" },
    { sharedTo: "test" }
  ]
})

你到底试过什么问题?当你显然已经做了一些努力时,人们通常乐于提供帮助,但在这个问题上没有任何质疑。此外,这里实际上根本没有“嵌套数组”组件。我真诚地建议您阅读核心文档,因为您似乎不熟悉MongoDB查询的基础知识。这将有助于你,并减轻你遇到的每一件新事物都需要发布一个问题的需要。MongoDB真的不在乎你的字符串是否在数组中。如果链接的答案和文档不够清晰,那么这基本上可以通过
.find({“$or”:[{“createdBy”:“test”},{“sharedTo”:“test”}]})来解决。
你也应该看看
$elemMatch
操作符。@Dijkstra你真的不应该这样做。这与
$elemMatch
无关。我建议您查看核心文档,以便您也能真正理解何时以及为什么使用
$elemMatch
。“这不是那种情况。”尼尔伦谢谢你的建议。我真的很感激。