我从mongodb返回一个json结果,每个元素旁边都有数组 我想查询数组元素以找到特定的节点, 而不使用ID或电子邮件作为过滤器仅将令牌号作为过滤器(其唯一号)
this is how one of the items json looks like
{
"_id" : ObjectId("5cf67ad97739bfe8525e5353"),
"Email" : "eyal@gmail.com",
"Username" : "eyal",
"Password" : "1234",
"Tokens" : [
{
"Tokennumber" : "123",
"Valid" : "true",
"LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
},
{
"Tokennumber" : "124",
"Valid" : "false",
"LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
},
{
"Tokennumber" : "555",
"Valid" : true,
"LoginDate" : ISODate("2019-06-07T08:32:01.854Z")
}
]
}
I would like to query the json using only one parameter Tokennumber=555
令牌号是唯一的,所以我需要通过他的令牌号查询来获取整个节点
the expected result would be the node
with this
data
"_id" : ObjectId("5cf67ad97739bfe8525e5353"),
"Email" : "eyal@gmail.com",
"Username" : "eyal",
"Password" : "1234",
答案 0 :(得分:0)
您可以使用过滤器访问节点类型。
例如:
var filter = Builders<YourObject>.Filter.Eq(x => x.Tokens.Any(t => t.Tokennumber == tokerNume), true);
var result = MongoContext.MongoDatabase.GetCollection<YourObject>("YourDocument").Find(filter).FirstOrDefault();
答案 1 :(得分:0)
以下mongo查询使用$ elemMatch完成工作
db.User.aggregate({
"$match": {
"Tokens": {
"$elemMatch": {
"TokenNumber": "234"
}
}
}
})
这是生成上述聚合管道的c#代码。它使用的是MongoDB.Entities,它只是官方驱动程序的包装。 [免责声明:我是作者]
using MongoDB.Entities;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class User : Entity
{
public string Email { get; set; }
public Token[] Tokens { get; set; }
}
public class Token
{
public string TokenNumber { get; set; }
public bool Valid { get; set; }
}
static void Main(string[] args)
{
new DB("test");
(new User
{
Email = "email@domain.com",
Tokens = new[] {
new Token{ TokenNumber="123",Valid = false },
new Token{ TokenNumber="234",Valid = true },
new Token{ TokenNumber="456",Valid = false },
}
}).Save();
var user = DB.Queryable<User>()
.Where(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.Single();
}
}
}
编辑: 由于您提到无法使用该库,因此以下是使用官方驱动程序的方法:
var filter = Builders<User>.Filter
.ElemMatch(u => u.Tokens,
t => t.TokenNumber == "234");
var user = collection.Find(filter)
.Single();
var user = collection.Aggregate()
.Match(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.ToList()
.Single();
var user = collection.AsQueryable()
.Where(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.Single();