我在Mongodb中有一个文档模式,如下所示:

{
    _id: 1
    tags: [{
        tag: 'foo'
        links: [{
            link: 'http:www.google.com'
            date: '123'
        }] 
    }]
}

我试图将一个链接推送到"链接"数组中,该数组将是文档的唯一链接.

我的第一个问题...

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo'}}}, 
    {upsert: true}
)

给我这个(如果不存在,创建标签)

{ "_id" : 1, "tags" : [ { "tag" : "foo" } ] }

然后我继续问这个问题...

db.userlinks.update (
    {_id: 1, tags: {tag: 'foo', links: {$nin: [{link: 'http://www.google.com'}]}}}, 
    {$push: {tags: {tag: 'foo', links: {link: 'http://www.google.com', date: '123'}}}}, 
    {upsert: true}
)

但我得到了这个错误:"无法将$push/$pushAll修饰符应用于非数组"

我很确定问题出在我第二个查询的"更新"部分,但我不确定如何解决它.任何帮助都将不胜感激.

EDIT

我的第一个问题是...(感谢乔)

db.userlinks.update (
    {_id: 1, tags: {$nin: [{tag:'foo'}]}}, 
    {$push: {'tags': {tag:'foo', links:[]}}}, 
    {upsert: true}
)

我的第二个问题是...

db.userlinks.update (
    {_id: 1, 'tags.tag': 'foo'}, 
    {$push: {'tags.$.links': {link: 'http://www.google.com', date: '123'} } }
)

它成功地将链接推送到"链接"数组中,但也允许重复.我不允许重复链接$addToSet是一种工作方式,但是如果日期发生变化,它仍然会插入一个重复的链接.

有没有办法在我的第二个查询的"查询"部分判断链接的存在,或者在某些字段匹配的情况下只判断addToSet?

推荐答案

我终于明白了...尽管如果有人能找到更好的方法,请添加它作为答案.

// create the userlinks collection if it doesn't exist
// also add a tag 'foo' into it, but only if the tag doesn't exist
db.userlinks.update (
    {_id: '1', 'tags.tag': {$nin: ['foo']}}, 
    {$push: {'tags': {tag:'foo', links:[]}}},
    {upsert: true}
)

// add a link into the 'foo' tag, but only if the link doesn't exist
db.userlinks.update(
    {_id: '1', 'tags.tag': 'foo', 'tags.links.link': {$nin: ['http://foobar.com']}},
    {$push: {'tags.$.links': {link: 'http://foobar.com', date: '15'} } }
)

Mongodb相关问答推荐

Mongo聚合项目数组交集

Go mongo-驱动程序测试,FindOne未根据给定的筛选器返回正确结果

MongoDB 对特定搜索查询的响应时间较长

MongoDB 聚合 groupBy 日期并计算子文档

MongoDB 按 created_at 月聚合

mongodb.将文档分组在数组中,对它们进行评分计数和求和并添加新字段

DB.collection('comments').find() 不工作

Mongoose - $project 嵌套的对象数组到数组的根级别

找到一个用户,然后使用 MongoDB 根据他们的总分获得他们的排名

MongoDB 聚合使用 $match 和 $expr 和数组

将子文档中的所有字段设置为 false,然后在单个查询中将第二个字段设置为 true

MongoDB - 在 $lookup 管道中匹配键匹配不起作用

从嵌套数组中 id 匹配的另一个集合中获取所有字段

Spring Data + MongoDB GridFS 可以通过 Repository 访问吗?

MongoError:$subtract 累加​​器是一元运算符

mongo _id 字段重复键错误

根据 Month 删除 mongodb 中的旧记录

请按语法排序 Mongoid Scope

MongoDB如何判断是否存在

RoboMongo:不显示所有文档